From e559f6f15080e3d0e0df018cf76db17d31bf0ab4 Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Sun, 17 Sep 2023 20:30:20 +0200 Subject: [PATCH] Parquet Reader Added reading MAP logical types Added reading LIST type Fixed nullable lists handling First implementation of Dremel encoding Added logging to Dremel algorithm Reconstruction of nested data structures based on schema definition Performance optimization Attempt to read map with values as a lists Rebuilding structures Extracted rebuilding columns logic to ColumnBuilder class Reading nested structures Restored usage of flow array functions Added dremel/parquet to test suite Updated github workflows Avoid calculating remaining lenght/current position in BinaryReader on the fly Make DataSize value object mutable Move reading multiple values from Buffer into BufferReader Allow to read from stream Retrieve column chunks as generator Moved reading flat columns into generics Read parquet files struct columns through generators Fixed reading column chunks Reduced number of iterations over generators Keep stream offset to avoid generators overlapping Read all column chunks from a row group at once to avoid dealing with rows split between pages Added notes for performance optimizations Added PageByPage ChunkReader implementation Fixed reding bytes of array when it's not a string Adjusted schema ddl generation Allow to limit numbers of returned rows Fixed limit when there is more than one column chunk Adjusted composer.json files in all subrepos Added Parquet Reader options - handling INT96 as DateTime, reading byte arrays as strings, convert nanos to micros timestamps Marked codename parquet extractor as deprecated Added snappy extension detection Converted testsuite fixtures into gzip from snappy Fixed issues related to missing snapy_uncompress function Added python scripts used to generate test/fixtures data for reader Added resources folder into gitattributes as export-igonre --- .github/labeler.yml | 6 + .github/workflows/monorepo-split.yml | 6 +- composer.json | 22 +- composer.lock | 999 +++++++-------- phpstan.neon | 4 + phpunit.xml | 4 + psalm.xml | 5 + .../Parquet/Codename/ParquetExtractor.php | 3 + .../ETL/Adapter/Parquet/ParquetExtractor.php | 78 ++ .../src/Flow/ETL/DSL/Parquet.php | 13 +- .../Integration/Codename/ParquetTest.php | 18 +- src/core/etl/composer.json | 3 +- src/core/etl/src/Flow/ETL/Rows.php | 28 + .../tests/Flow/ETL/Tests/Unit/RowsTest.php | 39 + src/lib/dremel/.gitattributes | 9 + .../dremel/.github/workflows/readonly.yaml | 17 + src/lib/dremel/CONTRIBUTING.md | 6 + src/lib/dremel/LICENSE | 21 + src/lib/dremel/README.md | 7 + src/lib/dremel/composer.json | 36 + src/lib/dremel/src/Flow/Dremel/Dremel.php | 192 +++ .../Exception/InvalidArgumentException.php | 7 + .../Dremel/Exception/RuntimeException.php | 7 + src/lib/dremel/src/Flow/Dremel/ListNode.php | 102 ++ src/lib/dremel/src/Flow/Dremel/Node.php | 8 + src/lib/dremel/src/Flow/Dremel/NullNode.php | 20 + src/lib/dremel/src/Flow/Dremel/Stack.php | 84 ++ .../Flow/Dremel/Tests/Unit/DremelTest.php | 351 ++++++ .../Flow/Dremel/Tests/Unit/ListNodeTest.php | 214 ++++ src/lib/parquet/.gitattributes | 10 + .../parquet/.github/workflows/readonly.yaml | 17 + src/lib/parquet/CONTRIBUTING.md | 6 + src/lib/parquet/LICENSE | 21 + src/lib/parquet/README.md | 7 + src/lib/parquet/composer.json | 40 + src/lib/parquet/resources/python/.gitignore | 3 + src/lib/parquet/resources/python/README.md | 27 + .../resources/python/generators/lists.py | 78 ++ .../resources/python/generators/maps.py | 193 +++ .../resources/python/generators/orders.py | 84 ++ .../resources/python/generators/primitives.py | 110 ++ .../resources/python/generators/structs.py | 393 ++++++ .../parquet/resources/python/output/.gitkeep | 0 .../parquet/resources/python/requirements.txt | 3 + .../parquet/src/Flow/Parquet/BinaryReader.php | 99 ++ .../BinaryReader/BinaryBufferReader.php | 417 +++++++ .../BinaryReader/BinaryStreamReader.php | 299 +++++ .../src/Flow/Parquet/BinaryReader/Bytes.php | 113 ++ .../parquet/src/Flow/Parquet/ByteOrder.php | 9 + src/lib/parquet/src/Flow/Parquet/DataSize.php | 52 + .../Exception/InvalidArgumentException.php | 7 + .../Exception/OutOfBoundsException.php | 7 + .../Parquet/Exception/RuntimeException.php | 7 + src/lib/parquet/src/Flow/Parquet/Option.php | 30 + src/lib/parquet/src/Flow/Parquet/Options.php | 32 + .../parquet/src/Flow/Parquet/ParquetFile.php | 335 +++++ .../src/Flow/Parquet/ParquetFile/Codec.php | 33 + .../Parquet/ParquetFile/ColumnChunkReader.php | 14 + .../ColumnChunkReader/PageByPage.php | 118 ++ .../ColumnChunkReader/WholeChunk.php | 85 ++ .../Flow/Parquet/ParquetFile/Compressions.php | 15 + .../ParquetFile/Data/BytesConverter.php | 59 + .../Parquet/ParquetFile/Data/DataBuilder.php | 211 ++++ .../ParquetFile/Data/RLEBitPackedHybrid.php | 131 ++ .../Flow/Parquet/ParquetFile/DataCoder.php | 243 ++++ .../Flow/Parquet/ParquetFile/Encodings.php | 16 + .../src/Flow/Parquet/ParquetFile/Metadata.php | 78 ++ .../Parquet/ParquetFile/Page/ColumnData.php | 159 +++ .../Parquet/ParquetFile/Page/Dictionary.php | 10 + .../Page/Header/DataPageHeader.php | 26 + .../Page/Header/DataPageHeaderV2.php | 21 + .../Page/Header/DictionaryPageHeader.php | 26 + .../Parquet/ParquetFile/Page/Header/Type.php | 16 + .../Parquet/ParquetFile/Page/PageHeader.php | 136 +++ .../Flow/Parquet/ParquetFile/PageReader.php | 79 ++ .../src/Flow/Parquet/ParquetFile/RowGroup.php | 25 + .../ParquetFile/RowGroup/ColumnChunk.php | 136 +++ .../ParquetFile/RowGroup/Statistics.php | 19 + .../Flow/Parquet/ParquetFile/RowGroups.php | 33 + .../src/Flow/Parquet/ParquetFile/Schema.php | 196 +++ .../Parquet/ParquetFile/Schema/Column.php | 38 + .../Parquet/ParquetFile/Schema/FlatColumn.php | 203 +++ .../ParquetFile/Schema/LogicalType.php | 121 ++ .../Schema/LogicalType/TimeUnit.php | 10 + .../Schema/LogicalType/Timestamp.php | 35 + .../ParquetFile/Schema/NestedColumn.php | 263 ++++ .../ParquetFile/Schema/PhysicalType.php | 15 + .../Parquet/ParquetFile/Schema/Repetition.php | 10 + src/lib/parquet/src/Flow/Parquet/Reader.php | 62 + .../Parquet/Resources/Thrift/parquet.thrift | 1087 +++++++++++++++++ .../Resources/Thrift/parquet_clean.thrift | 354 ++++++ .../src/Flow/Parquet/Thrift/AesGcmCtrV1.php | 79 ++ .../src/Flow/Parquet/Thrift/AesGcmV1.php | 79 ++ .../Parquet/Thrift/BloomFilterAlgorithm.php | 58 + .../Parquet/Thrift/BloomFilterCompression.php | 53 + .../Flow/Parquet/Thrift/BloomFilterHash.php | 59 + .../Flow/Parquet/Thrift/BloomFilterHeader.php | 97 ++ .../src/Flow/Parquet/Thrift/BoundaryOrder.php | 29 + .../src/Flow/Parquet/Thrift/BsonType.php | 43 + .../src/Flow/Parquet/Thrift/ColumnChunk.php | 155 +++ .../Parquet/Thrift/ColumnCryptoMetaData.php | 64 + .../src/Flow/Parquet/Thrift/ColumnIndex.php | 135 ++ .../Flow/Parquet/Thrift/ColumnMetaData.php | 255 ++++ .../src/Flow/Parquet/Thrift/ColumnOrder.php | 114 ++ .../Flow/Parquet/Thrift/CompressionCodec.php | 49 + .../src/Flow/Parquet/Thrift/ConvertedType.php | 185 +++ .../Flow/Parquet/Thrift/DataPageHeader.php | 109 ++ .../Flow/Parquet/Thrift/DataPageHeaderV2.php | 150 +++ .../src/Flow/Parquet/Thrift/DateType.php | 38 + .../src/Flow/Parquet/Thrift/DecimalType.php | 73 ++ .../Parquet/Thrift/DictionaryPageHeader.php | 84 ++ .../src/Flow/Parquet/Thrift/Encoding.php | 95 ++ .../Parquet/Thrift/EncryptionAlgorithm.php | 64 + .../Thrift/EncryptionWithColumnKey.php | 70 ++ .../Thrift/EncryptionWithFooterKey.php | 38 + .../src/Flow/Parquet/Thrift/EnumType.php | 38 + .../Parquet/Thrift/FieldRepetitionType.php | 37 + .../Parquet/Thrift/FileCryptoMetaData.php | 73 ++ .../src/Flow/Parquet/Thrift/FileMetaData.php | 197 +++ .../Flow/Parquet/Thrift/IndexPageHeader.php | 38 + .../src/Flow/Parquet/Thrift/IntType.php | 69 ++ .../src/Flow/Parquet/Thrift/JsonType.php | 43 + .../src/Flow/Parquet/Thrift/KeyValue.php | 65 + .../src/Flow/Parquet/Thrift/ListType.php | 38 + .../src/Flow/Parquet/Thrift/LogicalType.php | 192 +++ .../src/Flow/Parquet/Thrift/MapType.php | 38 + .../src/Flow/Parquet/Thrift/MicroSeconds.php | 38 + .../src/Flow/Parquet/Thrift/MilliSeconds.php | 41 + .../src/Flow/Parquet/Thrift/NanoSeconds.php | 38 + .../src/Flow/Parquet/Thrift/NullType.php | 45 + .../src/Flow/Parquet/Thrift/OffsetIndex.php | 60 + .../Flow/Parquet/Thrift/PageEncodingStats.php | 83 ++ .../src/Flow/Parquet/Thrift/PageHeader.php | 150 +++ .../src/Flow/Parquet/Thrift/PageLocation.php | 80 ++ .../src/Flow/Parquet/Thrift/PageType.php | 27 + .../src/Flow/Parquet/Thrift/RowGroup.php | 140 +++ .../src/Flow/Parquet/Thrift/SchemaElement.php | 187 +++ .../src/Flow/Parquet/Thrift/SortingColumn.php | 82 ++ .../Parquet/Thrift/SplitBlockAlgorithm.php | 41 + .../src/Flow/Parquet/Thrift/Statistics.php | 127 ++ .../src/Flow/Parquet/Thrift/StringType.php | 41 + .../src/Flow/Parquet/Thrift/TimeType.php | 68 ++ .../src/Flow/Parquet/Thrift/TimeUnit.php | 75 ++ .../src/Flow/Parquet/Thrift/TimestampType.php | 68 ++ .../parquet/src/Flow/Parquet/Thrift/Type.php | 46 + .../Flow/Parquet/Thrift/TypeDefinedOrder.php | 41 + .../src/Flow/Parquet/Thrift/UUIDType.php | 38 + .../src/Flow/Parquet/Thrift/Uncompressed.php | 41 + .../src/Flow/Parquet/Thrift/XxHash.php | 42 + .../parquet/src/Flow/Parquet/functions.php | 46 + .../Flow/Parquet/Tests/Fixtures/lists.json | 1 + .../Flow/Parquet/Tests/Fixtures/lists.parquet | Bin 0 -> 4772 bytes .../Flow/Parquet/Tests/Fixtures/maps.json | 1 + .../Flow/Parquet/Tests/Fixtures/maps.parquet | Bin 0 -> 17362 bytes .../Parquet/Tests/Fixtures/primitives.json | 1 + .../Parquet/Tests/Fixtures/primitives.parquet | Bin 0 -> 15690 bytes .../Flow/Parquet/Tests/Fixtures/structs.json | 1 + .../Parquet/Tests/Fixtures/structs.parquet | Bin 0 -> 33663 bytes .../Tests/Integration/ListsReadingTest.php | 127 ++ .../Tests/Integration/MapsReadingTest.php | 199 +++ .../ParquetIntegrationTestCase.php | 25 + .../Tests/Integration/SchemaReadingTest.php | 44 + .../Integration/SimpleTypesReadingTest.php | 404 ++++++ .../Tests/Integration/StructsReadingTest.php | 242 ++++ .../BinaryReader/BinaryBufferReaderTest.php | 122 ++ .../Tests/Unit/BinaryReader/BytesTest.php | 84 ++ .../Unit/Data/RLEBitPackedHybridTest.php | 167 +++ .../Flow/Parquet/Tests/Unit/FunctionsTest.php | 42 + .../Unit/ParquetFile/Page/ColumnDataTest.php | 103 ++ 169 files changed, 14490 insertions(+), 512 deletions(-) create mode 100644 src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/ParquetExtractor.php create mode 100644 src/lib/dremel/.gitattributes create mode 100644 src/lib/dremel/.github/workflows/readonly.yaml create mode 100644 src/lib/dremel/CONTRIBUTING.md create mode 100644 src/lib/dremel/LICENSE create mode 100644 src/lib/dremel/README.md create mode 100644 src/lib/dremel/composer.json create mode 100644 src/lib/dremel/src/Flow/Dremel/Dremel.php create mode 100644 src/lib/dremel/src/Flow/Dremel/Exception/InvalidArgumentException.php create mode 100644 src/lib/dremel/src/Flow/Dremel/Exception/RuntimeException.php create mode 100644 src/lib/dremel/src/Flow/Dremel/ListNode.php create mode 100644 src/lib/dremel/src/Flow/Dremel/Node.php create mode 100644 src/lib/dremel/src/Flow/Dremel/NullNode.php create mode 100644 src/lib/dremel/src/Flow/Dremel/Stack.php create mode 100644 src/lib/dremel/tests/Flow/Dremel/Tests/Unit/DremelTest.php create mode 100644 src/lib/dremel/tests/Flow/Dremel/Tests/Unit/ListNodeTest.php create mode 100644 src/lib/parquet/.gitattributes create mode 100644 src/lib/parquet/.github/workflows/readonly.yaml create mode 100644 src/lib/parquet/CONTRIBUTING.md create mode 100644 src/lib/parquet/LICENSE create mode 100644 src/lib/parquet/README.md create mode 100644 src/lib/parquet/composer.json create mode 100644 src/lib/parquet/resources/python/.gitignore create mode 100644 src/lib/parquet/resources/python/README.md create mode 100644 src/lib/parquet/resources/python/generators/lists.py create mode 100644 src/lib/parquet/resources/python/generators/maps.py create mode 100644 src/lib/parquet/resources/python/generators/orders.py create mode 100644 src/lib/parquet/resources/python/generators/primitives.py create mode 100644 src/lib/parquet/resources/python/generators/structs.py create mode 100644 src/lib/parquet/resources/python/output/.gitkeep create mode 100644 src/lib/parquet/resources/python/requirements.txt create mode 100644 src/lib/parquet/src/Flow/Parquet/BinaryReader.php create mode 100644 src/lib/parquet/src/Flow/Parquet/BinaryReader/BinaryBufferReader.php create mode 100644 src/lib/parquet/src/Flow/Parquet/BinaryReader/BinaryStreamReader.php create mode 100644 src/lib/parquet/src/Flow/Parquet/BinaryReader/Bytes.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ByteOrder.php create mode 100644 src/lib/parquet/src/Flow/Parquet/DataSize.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Exception/InvalidArgumentException.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Exception/OutOfBoundsException.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Exception/RuntimeException.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Option.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Options.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Codec.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/ColumnChunkReader.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/ColumnChunkReader/PageByPage.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/ColumnChunkReader/WholeChunk.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Compressions.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Data/BytesConverter.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Data/DataBuilder.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Data/RLEBitPackedHybrid.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/DataCoder.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Encodings.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Metadata.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/ColumnData.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Dictionary.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Header/DataPageHeader.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Header/DataPageHeaderV2.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Header/DictionaryPageHeader.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Header/Type.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/PageHeader.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/PageReader.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroup.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroup/ColumnChunk.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroup/Statistics.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroups.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/Column.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/FlatColumn.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/LogicalType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/LogicalType/TimeUnit.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/LogicalType/Timestamp.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/NestedColumn.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/PhysicalType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/Repetition.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Reader.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Resources/Thrift/parquet.thrift create mode 100644 src/lib/parquet/src/Flow/Parquet/Resources/Thrift/parquet_clean.thrift create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/AesGcmCtrV1.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/AesGcmV1.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterAlgorithm.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterCompression.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterHash.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterHeader.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/BoundaryOrder.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/BsonType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/ColumnChunk.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/ColumnCryptoMetaData.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/ColumnIndex.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/ColumnMetaData.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/ColumnOrder.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/CompressionCodec.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/ConvertedType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/DataPageHeader.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/DataPageHeaderV2.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/DateType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/DecimalType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/DictionaryPageHeader.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/Encoding.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/EncryptionAlgorithm.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/EncryptionWithColumnKey.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/EncryptionWithFooterKey.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/EnumType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/FieldRepetitionType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/FileCryptoMetaData.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/FileMetaData.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/IndexPageHeader.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/IntType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/JsonType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/KeyValue.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/ListType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/LogicalType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/MapType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/MicroSeconds.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/MilliSeconds.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/NanoSeconds.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/NullType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/OffsetIndex.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/PageEncodingStats.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/PageHeader.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/PageLocation.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/PageType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/RowGroup.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/SchemaElement.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/SortingColumn.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/SplitBlockAlgorithm.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/Statistics.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/StringType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/TimeType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/TimeUnit.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/TimestampType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/Type.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/TypeDefinedOrder.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/UUIDType.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/Uncompressed.php create mode 100644 src/lib/parquet/src/Flow/Parquet/Thrift/XxHash.php create mode 100644 src/lib/parquet/src/Flow/Parquet/functions.php create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/lists.json create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/lists.parquet create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/maps.json create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/maps.parquet create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/primitives.json create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/primitives.parquet create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/structs.json create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/structs.parquet create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Integration/ListsReadingTest.php create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Integration/MapsReadingTest.php create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Integration/ParquetIntegrationTestCase.php create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Integration/SchemaReadingTest.php create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Integration/SimpleTypesReadingTest.php create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Integration/StructsReadingTest.php create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Unit/BinaryReader/BinaryBufferReaderTest.php create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Unit/BinaryReader/BytesTest.php create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Unit/Data/RLEBitPackedHybridTest.php create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Unit/FunctionsTest.php create mode 100644 src/lib/parquet/tests/Flow/Parquet/Tests/Unit/ParquetFile/Page/ColumnDataTest.php diff --git a/.github/labeler.yml b/.github/labeler.yml index 21ee79355..19c5f69d3 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -13,6 +13,10 @@ lib-array-dot: - any: ["src/lib/array-dot/**/*"] lib-doctrine-dbal-bulk: - any: ["src/lib/doctrine-dbal-bulk/**/*"] +lib-parquet: + - any: ["src/lib/parquet/**/*"] +lib-dremel: + - any: ["src/lib/dremel/**/*"] adapter-amphp: - any: ["src/adapter/etl-adapter-amphp/**/*"] @@ -26,6 +30,8 @@ adapter-doctrine: - any: ["src/adapter/etl-adapter-doctrine/**/*"] adapter-elasticsearch: - any: ["src/adapter/etl-adapter-elasticsearch/**/*"] +adapter-meilisearch: + - any: ["src/adapter/etl-adapter-meilisearch/**/*"] adapter-google-sheet: - any: ["src/adapter/etl-adapter-google-sheet/**/*"] adapter-http: diff --git a/.github/workflows/monorepo-split.yml b/.github/workflows/monorepo-split.yml index cc5a82c4e..a0c966369 100644 --- a/.github/workflows/monorepo-split.yml +++ b/.github/workflows/monorepo-split.yml @@ -26,6 +26,10 @@ jobs: split_repository: 'array-dot' - local_path: 'src/lib/doctrine-dbal-bulk' split_repository: 'doctrine-dbal-bulk' + - local_path: 'src/lib/parquet' + split_repository: 'parquet' + - local_path: 'src/lib/dremel' + split_repository: 'dremel' - local_path: 'src/adapter/etl-adapter-amphp' split_repository: 'etl-adapter-amphp' @@ -40,7 +44,7 @@ jobs: - local_path: 'src/adapter/etl-adapter-elasticsearch' split_repository: 'etl-adapter-elasticsearch' - local_path: 'src/adapter/etl-adapter-meilisearch' - split_repository: 'etl-adapter-meilisearch' + split_repository: 'etl-adapter-meilisearch' - local_path: 'src/adapter/etl-adapter-google-sheet' split_repository: 'etl-adapter-google-sheet' - local_path: 'src/adapter/etl-adapter-http' diff --git a/composer.json b/composer.json index d118326ae..58f814f3d 100644 --- a/composer.json +++ b/composer.json @@ -11,6 +11,7 @@ "license": "MIT", "require": { "php": "~8.1 || ~8.2", + "ext-bcmath": "*", "ext-dom": "*", "ext-hash": "*", "ext-json": "*", @@ -25,7 +26,9 @@ "google/apiclient": "^2.13", "halaxa/json-machine": "^1.0", "league/flysystem": "^3.0", + "meilisearch/meilisearch-php": "^1.1", "monolog/monolog": "^3.0", + "packaged/thrift": "^0.15.0", "psr/http-client": "^1.0", "psr/log": "^2.0 || ^3.0", "psr/simple-cache": "^1.0 || ^2.0 || ^3.0", @@ -41,7 +44,6 @@ "laravel/serializable-closure": "^1.1", "league/flysystem-aws-s3-v3": "^3.0", "league/flysystem-azure-blob-storage": "^3.0", - "meilisearch/meilisearch-php": "^1.1", "moneyphp/money": "^4", "nyholm/psr7": "^1.4", "php-http/curl-client": "^2.2", @@ -56,7 +58,8 @@ "files": [ "build/version.php", "src/core/etl/src/Flow/ETL/DSL/functions.php", - "src/lib/array-dot/src/Flow/ArrayDot/array_dot.php" + "src/lib/array-dot/src/Flow/ArrayDot/array_dot.php", + "src/lib/parquet/src/Flow/Parquet/functions.php" ], "psr-4": { "Flow\\": [ @@ -77,7 +80,9 @@ "src/adapter/etl-adapter-xml/src/Flow", "src/core/etl/src/Flow", "src/lib/array-dot/src/Flow", - "src/lib/doctrine-dbal-bulk/src/Flow" + "src/lib/doctrine-dbal-bulk/src/Flow", + "src/lib/dremel/src/Flow", + "src/lib/parquet/src/Flow" ], "Flow\\Doctrine\\Bulk\\": [ "src/lib/doctrine-dbal-bulk/src/Flow/Doctrine/Bulk" @@ -92,8 +97,8 @@ "Flow\\": [ "src/adapter/etl-adapter-amphp/tests/Flow", "src/adapter/etl-adapter-avro/tests/Flow", - "src/adapter/etl-adapter-csv/tests/Flow", "src/adapter/etl-adapter-chartjs/tests/Flow", + "src/adapter/etl-adapter-csv/tests/Flow", "src/adapter/etl-adapter-doctrine/tests/Flow", "src/adapter/etl-adapter-elasticsearch/tests/Flow", "src/adapter/etl-adapter-google-sheet/tests/Flow", @@ -107,7 +112,9 @@ "src/adapter/etl-adapter-xml/tests/Flow", "src/core/etl/tests/Flow", "src/lib/array-dot/tests/Flow", - "src/lib/doctrine-dbal-bulk/tests/Flow" + "src/lib/doctrine-dbal-bulk/tests/Flow", + "src/lib/dremel/tests/Flow", + "src/lib/parquet/tests/Flow" ], "Flow\\Doctrine\\Bulk\\Tests\\": [ "src/lib/doctrine-dbal-bulk/tests/Flow/Doctrine/Bulk/Tests" @@ -126,11 +133,12 @@ "flow-php/array-dot": "self.version", "flow-php/doctrine-dbal-bulk": "self.version", "flow-php/doctrine-dbal-bulk-tools": "self.version", + "flow-php/dremel": "self.version", "flow-php/etl": "self.version", "flow-php/etl-adapter-amphp": "self.version", "flow-php/etl-adapter-avro": "self.version", - "flow-php/etl-adapter-csv": "self.version", "flow-php/etl-adapter-chartjs": "self.version", + "flow-php/etl-adapter-csv": "self.version", "flow-php/etl-adapter-dbal-tools": "self.version", "flow-php/etl-adapter-doctrine": "self.version", "flow-php/etl-adapter-elasticsearch": "self.version", @@ -144,7 +152,7 @@ "flow-php/etl-adapter-reactphp": "self.version", "flow-php/etl-adapter-text": "self.version", "flow-php/etl-adapter-xml": "self.version", - "flow-php/etl-tools": "self.version" + "flow-php/parquet": "self.version" }, "scripts": { "build": [ diff --git a/composer.lock b/composer.lock index 0f3a24573..93ea3747a 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "6de5d25741b658ad50f4794e782cdab8", + "content-hash": "de28f6799b1475e489d12f20e7926842", "packages": [ { "name": "amphp/amp", @@ -781,6 +781,72 @@ ], "time": "2023-01-09T22:29:20+00:00" }, + { + "name": "clue/stream-filter", + "version": "v1.6.0", + "source": { + "type": "git", + "url": "https://github.com/clue/stream-filter.git", + "reference": "d6169430c7731d8509da7aecd0af756a5747b78e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/clue/stream-filter/zipball/d6169430c7731d8509da7aecd0af756a5747b78e", + "reference": "d6169430c7731d8509da7aecd0af756a5747b78e", + "shasum": "" + }, + "require": { + "php": ">=5.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.36" + }, + "type": "library", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "Clue\\StreamFilter\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering" + } + ], + "description": "A simple and modern approach to stream filtering in PHP", + "homepage": "https://github.com/clue/php-stream-filter", + "keywords": [ + "bucket brigade", + "callback", + "filter", + "php_user_filter", + "stream", + "stream_filter_append", + "stream_filter_register" + ], + "support": { + "issues": "https://github.com/clue/stream-filter/issues", + "source": "https://github.com/clue/stream-filter/tree/v1.6.0" + }, + "funding": [ + { + "url": "https://clue.engineering/support", + "type": "custom" + }, + { + "url": "https://github.com/clue", + "type": "github" + } + ], + "time": "2022-02-21T13:15:14+00:00" + }, { "name": "codename/parquet", "version": "v0.7.0", @@ -972,16 +1038,16 @@ }, { "name": "doctrine/dbal", - "version": "3.7.0", + "version": "3.7.1", "source": { "type": "git", "url": "https://github.com/doctrine/dbal.git", - "reference": "00d03067f07482f025d41ab55e4ba0db5eca2cdf" + "reference": "5b7bd66c9ff58c04c5474ab85edce442f8081cb2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/dbal/zipball/00d03067f07482f025d41ab55e4ba0db5eca2cdf", - "reference": "00d03067f07482f025d41ab55e4ba0db5eca2cdf", + "url": "https://api.github.com/repos/doctrine/dbal/zipball/5b7bd66c9ff58c04c5474ab85edce442f8081cb2", + "reference": "5b7bd66c9ff58c04c5474ab85edce442f8081cb2", "shasum": "" }, "require": { @@ -1065,7 +1131,7 @@ ], "support": { "issues": "https://github.com/doctrine/dbal/issues", - "source": "https://github.com/doctrine/dbal/tree/3.7.0" + "source": "https://github.com/doctrine/dbal/tree/3.7.1" }, "funding": [ { @@ -1081,7 +1147,7 @@ "type": "tidelift" } ], - "time": "2023-09-26T20:56:55+00:00" + "time": "2023-10-06T05:06:20+00:00" }, { "name": "doctrine/deprecations", @@ -1374,16 +1440,16 @@ }, { "name": "firebase/php-jwt", - "version": "v6.8.1", + "version": "v6.9.0", "source": { "type": "git", "url": "https://github.com/firebase/php-jwt.git", - "reference": "5dbc8959427416b8ee09a100d7a8588c00fb2e26" + "reference": "f03270e63eaccf3019ef0f32849c497385774e11" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/firebase/php-jwt/zipball/5dbc8959427416b8ee09a100d7a8588c00fb2e26", - "reference": "5dbc8959427416b8ee09a100d7a8588c00fb2e26", + "url": "https://api.github.com/repos/firebase/php-jwt/zipball/f03270e63eaccf3019ef0f32849c497385774e11", + "reference": "f03270e63eaccf3019ef0f32849c497385774e11", "shasum": "" }, "require": { @@ -1431,9 +1497,9 @@ ], "support": { "issues": "https://github.com/firebase/php-jwt/issues", - "source": "https://github.com/firebase/php-jwt/tree/v6.8.1" + "source": "https://github.com/firebase/php-jwt/tree/v6.9.0" }, - "time": "2023-07-14T18:33:00+00:00" + "time": "2023-10-05T00:24:42+00:00" }, { "name": "flix-tech/avro-php", @@ -1547,16 +1613,16 @@ }, { "name": "google/apiclient-services", - "version": "v0.318.0", + "version": "v0.319.0", "source": { "type": "git", "url": "https://github.com/googleapis/google-api-php-client-services.git", - "reference": "908a866797b9731352e650997112c8c3a0347ac5" + "reference": "9206f4d8cfacbec3c494d68f1758b2c8ca5b179d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/googleapis/google-api-php-client-services/zipball/908a866797b9731352e650997112c8c3a0347ac5", - "reference": "908a866797b9731352e650997112c8c3a0347ac5", + "url": "https://api.github.com/repos/googleapis/google-api-php-client-services/zipball/9206f4d8cfacbec3c494d68f1758b2c8ca5b179d", + "reference": "9206f4d8cfacbec3c494d68f1758b2c8ca5b179d", "shasum": "" }, "require": { @@ -1585,22 +1651,22 @@ ], "support": { "issues": "https://github.com/googleapis/google-api-php-client-services/issues", - "source": "https://github.com/googleapis/google-api-php-client-services/tree/v0.318.0" + "source": "https://github.com/googleapis/google-api-php-client-services/tree/v0.319.0" }, - "time": "2023-10-02T01:10:14+00:00" + "time": "2023-10-08T01:02:14+00:00" }, { "name": "google/auth", - "version": "v1.30.0", + "version": "v1.31.0", "source": { "type": "git", "url": "https://github.com/googleapis/google-auth-library-php.git", - "reference": "6028b072aa444d7edecbed603431322026704627" + "reference": "22209fddd0c06f3f8e3cb4aade0b352aa00f9888" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/googleapis/google-auth-library-php/zipball/6028b072aa444d7edecbed603431322026704627", - "reference": "6028b072aa444d7edecbed603431322026704627", + "url": "https://api.github.com/repos/googleapis/google-auth-library-php/zipball/22209fddd0c06f3f8e3cb4aade0b352aa00f9888", + "reference": "22209fddd0c06f3f8e3cb4aade0b352aa00f9888", "shasum": "" }, "require": { @@ -1643,9 +1709,9 @@ "support": { "docs": "https://googleapis.github.io/google-auth-library-php/main/", "issues": "https://github.com/googleapis/google-auth-library-php/issues", - "source": "https://github.com/googleapis/google-auth-library-php/tree/v1.30.0" + "source": "https://github.com/googleapis/google-auth-library-php/tree/v1.31.0" }, - "time": "2023-09-07T19:13:44+00:00" + "time": "2023-10-05T20:39:00+00:00" }, { "name": "guzzlehttp/guzzle", @@ -2090,16 +2156,16 @@ }, { "name": "league/flysystem", - "version": "3.16.0", + "version": "3.17.0", "source": { "type": "git", "url": "https://github.com/thephpleague/flysystem.git", - "reference": "4fdf372ca6b63c6e281b1c01a624349ccb757729" + "reference": "bd4c9b26849d82364119c68429541f1631fba94b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/4fdf372ca6b63c6e281b1c01a624349ccb757729", - "reference": "4fdf372ca6b63c6e281b1c01a624349ccb757729", + "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/bd4c9b26849d82364119c68429541f1631fba94b", + "reference": "bd4c9b26849d82364119c68429541f1631fba94b", "shasum": "" }, "require": { @@ -2117,8 +2183,8 @@ "symfony/http-client": "<5.2" }, "require-dev": { - "async-aws/s3": "^1.5", - "async-aws/simple-s3": "^1.1", + "async-aws/s3": "^1.5 || ^2.0", + "async-aws/simple-s3": "^1.1 || ^2.0", "aws/aws-sdk-php": "^3.220.0", "composer/semver": "^3.0", "ext-fileinfo": "*", @@ -2164,7 +2230,7 @@ ], "support": { "issues": "https://github.com/thephpleague/flysystem/issues", - "source": "https://github.com/thephpleague/flysystem/tree/3.16.0" + "source": "https://github.com/thephpleague/flysystem/tree/3.17.0" }, "funding": [ { @@ -2176,7 +2242,7 @@ "type": "github" } ], - "time": "2023-09-07T19:22:17+00:00" + "time": "2023-10-05T20:15:05+00:00" }, { "name": "league/flysystem-local", @@ -2468,6 +2534,74 @@ ], "time": "2023-09-09T17:21:43+00:00" }, + { + "name": "meilisearch/meilisearch-php", + "version": "v1.4.0", + "source": { + "type": "git", + "url": "https://github.com/meilisearch/meilisearch-php.git", + "reference": "956e2677b0cbbff8e9dfa658106097639bc9a507" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/meilisearch/meilisearch-php/zipball/956e2677b0cbbff8e9dfa658106097639bc9a507", + "reference": "956e2677b0cbbff8e9dfa658106097639bc9a507", + "shasum": "" + }, + "require": { + "ext-json": "*", + "php": "^7.4 || ^8.0", + "php-http/client-common": "^2.0", + "php-http/discovery": "^1.7", + "php-http/httplug": "^2.1" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.0", + "guzzlehttp/guzzle": "^7.1", + "http-interop/http-factory-guzzle": "^1.0", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan": "1.10.32", + "phpstan/phpstan-deprecation-rules": "^1.0", + "phpstan/phpstan-phpunit": "^1.0", + "phpstan/phpstan-strict-rules": "^1.1", + "phpunit/phpunit": "^9.5 || ^10.1" + }, + "suggest": { + "guzzlehttp/guzzle": "Use Guzzle ^7 as HTTP client", + "http-interop/http-factory-guzzle": "Factory for guzzlehttp/guzzle" + }, + "type": "library", + "autoload": { + "psr-4": { + "MeiliSearch\\": "src/", + "Meilisearch\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Clementine Urquizar", + "email": "clementine@meilisearch.com" + } + ], + "description": "PHP wrapper for the Meilisearch API", + "keywords": [ + "api", + "client", + "instant", + "meilisearch", + "php", + "search" + ], + "support": { + "issues": "https://github.com/meilisearch/meilisearch-php/issues", + "source": "https://github.com/meilisearch/meilisearch-php/tree/v1.4.0" + }, + "time": "2023-09-25T11:42:54+00:00" + }, { "name": "monolog/monolog", "version": "3.4.0", @@ -2778,6 +2912,75 @@ }, "time": "2016-04-12T05:46:52+00:00" }, + { + "name": "php-http/client-common", + "version": "2.7.0", + "source": { + "type": "git", + "url": "https://github.com/php-http/client-common.git", + "reference": "880509727a447474d2a71b7d7fa5d268ddd3db4b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-http/client-common/zipball/880509727a447474d2a71b7d7fa5d268ddd3db4b", + "reference": "880509727a447474d2a71b7d7fa5d268ddd3db4b", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0", + "php-http/httplug": "^2.0", + "php-http/message": "^1.6", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0 || ^2.0", + "symfony/options-resolver": "~4.0.15 || ~4.1.9 || ^4.2.1 || ^5.0 || ^6.0", + "symfony/polyfill-php80": "^1.17" + }, + "require-dev": { + "doctrine/instantiator": "^1.1", + "guzzlehttp/psr7": "^1.4", + "nyholm/psr7": "^1.2", + "phpspec/phpspec": "^5.1 || ^6.3 || ^7.1", + "phpspec/prophecy": "^1.10.2", + "phpunit/phpunit": "^7.5.20 || ^8.5.33 || ^9.6.7" + }, + "suggest": { + "ext-json": "To detect JSON responses with the ContentTypePlugin", + "ext-libxml": "To detect XML responses with the ContentTypePlugin", + "php-http/cache-plugin": "PSR-6 Cache plugin", + "php-http/logger-plugin": "PSR-3 Logger plugin", + "php-http/stopwatch-plugin": "Symfony Stopwatch plugin" + }, + "type": "library", + "autoload": { + "psr-4": { + "Http\\Client\\Common\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com" + } + ], + "description": "Common HTTP Client implementations and tools for HTTPlug", + "homepage": "http://httplug.io", + "keywords": [ + "client", + "common", + "http", + "httplug" + ], + "support": { + "issues": "https://github.com/php-http/client-common/issues", + "source": "https://github.com/php-http/client-common/tree/2.7.0" + }, + "time": "2023-05-17T06:46:59+00:00" + }, { "name": "php-http/discovery", "version": "1.19.1", @@ -2914,35 +3117,49 @@ "time": "2023-04-14T15:10:03+00:00" }, { - "name": "php-http/promise", - "version": "1.1.0", + "name": "php-http/message", + "version": "1.16.0", "source": { "type": "git", - "url": "https://github.com/php-http/promise.git", - "reference": "4c4c1f9b7289a2ec57cde7f1e9762a5789506f88" + "url": "https://github.com/php-http/message.git", + "reference": "47a14338bf4ebd67d317bf1144253d7db4ab55fd" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-http/promise/zipball/4c4c1f9b7289a2ec57cde7f1e9762a5789506f88", - "reference": "4c4c1f9b7289a2ec57cde7f1e9762a5789506f88", + "url": "https://api.github.com/repos/php-http/message/zipball/47a14338bf4ebd67d317bf1144253d7db4ab55fd", + "reference": "47a14338bf4ebd67d317bf1144253d7db4ab55fd", "shasum": "" }, "require": { - "php": "^7.1 || ^8.0" + "clue/stream-filter": "^1.5", + "php": "^7.2 || ^8.0", + "psr/http-message": "^1.1 || ^2.0" + }, + "provide": { + "php-http/message-factory-implementation": "1.0" }, "require-dev": { - "friends-of-phpspec/phpspec-code-coverage": "^4.3.2", - "phpspec/phpspec": "^5.1.2 || ^6.2" + "ergebnis/composer-normalize": "^2.6", + "ext-zlib": "*", + "guzzlehttp/psr7": "^1.0 || ^2.0", + "laminas/laminas-diactoros": "^2.0 || ^3.0", + "php-http/message-factory": "^1.0.2", + "phpspec/phpspec": "^5.1 || ^6.3 || ^7.1", + "slim/slim": "^3.0" }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.1-dev" - } + "suggest": { + "ext-zlib": "Used with compressor/decompressor streams", + "guzzlehttp/psr7": "Used with Guzzle PSR-7 Factories", + "laminas/laminas-diactoros": "Used with Diactoros Factories", + "slim/slim": "Used with Slim Framework PSR-7 implementation" }, + "type": "library", "autoload": { + "files": [ + "src/filters.php" + ], "psr-4": { - "Http\\Promise\\": "src/" + "Http\\Message\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", @@ -2950,17 +3167,72 @@ "MIT" ], "authors": [ - { - "name": "Joel Wurtz", - "email": "joel.wurtz@gmail.com" - }, { "name": "Márk Sági-Kazár", "email": "mark.sagikazar@gmail.com" } ], - "description": "Promise used for asynchronous HTTP requests", - "homepage": "http://httplug.io", + "description": "HTTP Message related tools", + "homepage": "http://php-http.org", + "keywords": [ + "http", + "message", + "psr-7" + ], + "support": { + "issues": "https://github.com/php-http/message/issues", + "source": "https://github.com/php-http/message/tree/1.16.0" + }, + "time": "2023-05-17T06:43:38+00:00" + }, + { + "name": "php-http/promise", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-http/promise.git", + "reference": "4c4c1f9b7289a2ec57cde7f1e9762a5789506f88" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-http/promise/zipball/4c4c1f9b7289a2ec57cde7f1e9762a5789506f88", + "reference": "4c4c1f9b7289a2ec57cde7f1e9762a5789506f88", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "friends-of-phpspec/phpspec-code-coverage": "^4.3.2", + "phpspec/phpspec": "^5.1.2 || ^6.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1-dev" + } + }, + "autoload": { + "psr-4": { + "Http\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Joel Wurtz", + "email": "joel.wurtz@gmail.com" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com" + } + ], + "description": "Promise used for asynchronous HTTP requests", + "homepage": "http://httplug.io", "keywords": [ "promise" ], @@ -4245,6 +4517,73 @@ ], "time": "2023-05-23T14:45:45+00:00" }, + { + "name": "symfony/options-resolver", + "version": "v6.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/options-resolver.git", + "reference": "a10f19f5198d589d5c33333cffe98dc9820332dd" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/a10f19f5198d589d5c33333cffe98dc9820332dd", + "reference": "a10f19f5198d589d5c33333cffe98dc9820332dd", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "symfony/deprecation-contracts": "^2.5|^3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\OptionsResolver\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides an improved replacement for the array_replace PHP function", + "homepage": "https://symfony.com", + "keywords": [ + "config", + "configuration", + "options" + ], + "support": { + "source": "https://github.com/symfony/options-resolver/tree/v6.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-05-12T14:21:09+00:00" + }, { "name": "symfony/polyfill-ctype", "version": "v1.28.0", @@ -4575,6 +4914,89 @@ ], "time": "2023-07-28T09:04:16+00:00" }, + { + "name": "symfony/polyfill-php80", + "version": "v1.28.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/6caa57379c4aec19c0a12a38b59b26487dcfe4b5", + "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-01-26T09:26:14+00:00" + }, { "name": "symfony/service-contracts", "version": "v3.3.0", @@ -4851,16 +5273,16 @@ }, { "name": "aws/aws-sdk-php", - "version": "3.282.0", + "version": "3.283.3", "source": { "type": "git", "url": "https://github.com/aws/aws-sdk-php.git", - "reference": "79a3ed5bb573f592823f8b1cffe0dbac3132e6b4" + "reference": "4cc8d6c7e856de80d9316f659c4c626d3713f6c1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/79a3ed5bb573f592823f8b1cffe0dbac3132e6b4", - "reference": "79a3ed5bb573f592823f8b1cffe0dbac3132e6b4", + "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/4cc8d6c7e856de80d9316f659c4c626d3713f6c1", + "reference": "4cc8d6c7e856de80d9316f659c4c626d3713f6c1", "shasum": "" }, "require": { @@ -4940,9 +5362,9 @@ "support": { "forum": "https://forums.aws.amazon.com/forum.jspa?forumID=80", "issues": "https://github.com/aws/aws-sdk-php/issues", - "source": "https://github.com/aws/aws-sdk-php/tree/3.282.0" + "source": "https://github.com/aws/aws-sdk-php/tree/3.283.3" }, - "time": "2023-09-28T18:09:20+00:00" + "time": "2023-10-12T18:14:56+00:00" }, { "name": "brick/math", @@ -5000,32 +5422,31 @@ "time": "2023-01-15T23:15:59+00:00" }, { - "name": "clue/stream-filter", - "version": "v1.6.0", + "name": "fig/log-test", + "version": "1.1.0", "source": { "type": "git", - "url": "https://github.com/clue/stream-filter.git", - "reference": "d6169430c7731d8509da7aecd0af756a5747b78e" + "url": "https://github.com/php-fig/log-test.git", + "reference": "02d6eaf8b09784b7adacf57a3c951bad95229a7f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/clue/stream-filter/zipball/d6169430c7731d8509da7aecd0af756a5747b78e", - "reference": "d6169430c7731d8509da7aecd0af756a5747b78e", + "url": "https://api.github.com/repos/php-fig/log-test/zipball/02d6eaf8b09784b7adacf57a3c951bad95229a7f", + "reference": "02d6eaf8b09784b7adacf57a3c951bad95229a7f", "shasum": "" }, "require": { - "php": ">=5.3" + "php": "^8.0", + "psr/log": "^2.0 | ^3.0" }, "require-dev": { - "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.36" + "phpunit/phpunit": "^8.0 | ^9.0", + "squizlabs/php_codesniffer": "^3.6" }, "type": "library", "autoload": { - "files": [ - "src/functions_include.php" - ], "psr-4": { - "Clue\\StreamFilter\\": "src/" + "Psr\\Log\\": "src" } }, "notification-url": "https://packagist.org/downloads/", @@ -5034,80 +5455,15 @@ ], "authors": [ { - "name": "Christian Lück", - "email": "christian@clue.engineering" + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/", + "role": "Organisation" } ], - "description": "A simple and modern approach to stream filtering in PHP", - "homepage": "https://github.com/clue/php-stream-filter", - "keywords": [ - "bucket brigade", - "callback", - "filter", - "php_user_filter", - "stream", - "stream_filter_append", - "stream_filter_register" - ], + "description": "Test utilities for the psr/log package that backs the PSR-3 specification.", "support": { - "issues": "https://github.com/clue/stream-filter/issues", - "source": "https://github.com/clue/stream-filter/tree/v1.6.0" - }, - "funding": [ - { - "url": "https://clue.engineering/support", - "type": "custom" - }, - { - "url": "https://github.com/clue", - "type": "github" - } - ], - "time": "2022-02-21T13:15:14+00:00" - }, - { - "name": "fig/log-test", - "version": "1.1.0", - "source": { - "type": "git", - "url": "https://github.com/php-fig/log-test.git", - "reference": "02d6eaf8b09784b7adacf57a3c951bad95229a7f" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/php-fig/log-test/zipball/02d6eaf8b09784b7adacf57a3c951bad95229a7f", - "reference": "02d6eaf8b09784b7adacf57a3c951bad95229a7f", - "shasum": "" - }, - "require": { - "php": "^8.0", - "psr/log": "^2.0 | ^3.0" - }, - "require-dev": { - "phpunit/phpunit": "^8.0 | ^9.0", - "squizlabs/php_codesniffer": "^3.6" - }, - "type": "library", - "autoload": { - "psr-4": { - "Psr\\Log\\": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "https://www.php-fig.org/", - "role": "Organisation" - } - ], - "description": "Test utilities for the psr/log package that backs the PSR-3 specification.", - "support": { - "issues": "https://github.com/php-fig/log-test/issues", - "source": "https://github.com/php-fig/log-test/tree/1.1.0" + "issues": "https://github.com/php-fig/log-test/issues", + "source": "https://github.com/php-fig/log-test/tree/1.1.0" }, "time": "2022-10-18T05:33:27+00:00" }, @@ -5355,74 +5711,6 @@ ], "time": "2023-08-30T10:22:50+00:00" }, - { - "name": "meilisearch/meilisearch-php", - "version": "v1.4.0", - "source": { - "type": "git", - "url": "https://github.com/meilisearch/meilisearch-php.git", - "reference": "956e2677b0cbbff8e9dfa658106097639bc9a507" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/meilisearch/meilisearch-php/zipball/956e2677b0cbbff8e9dfa658106097639bc9a507", - "reference": "956e2677b0cbbff8e9dfa658106097639bc9a507", - "shasum": "" - }, - "require": { - "ext-json": "*", - "php": "^7.4 || ^8.0", - "php-http/client-common": "^2.0", - "php-http/discovery": "^1.7", - "php-http/httplug": "^2.1" - }, - "require-dev": { - "friendsofphp/php-cs-fixer": "^3.0", - "guzzlehttp/guzzle": "^7.1", - "http-interop/http-factory-guzzle": "^1.0", - "phpstan/extension-installer": "^1.1", - "phpstan/phpstan": "1.10.32", - "phpstan/phpstan-deprecation-rules": "^1.0", - "phpstan/phpstan-phpunit": "^1.0", - "phpstan/phpstan-strict-rules": "^1.1", - "phpunit/phpunit": "^9.5 || ^10.1" - }, - "suggest": { - "guzzlehttp/guzzle": "Use Guzzle ^7 as HTTP client", - "http-interop/http-factory-guzzle": "Factory for guzzlehttp/guzzle" - }, - "type": "library", - "autoload": { - "psr-4": { - "MeiliSearch\\": "src/", - "Meilisearch\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Clementine Urquizar", - "email": "clementine@meilisearch.com" - } - ], - "description": "PHP wrapper for the Meilisearch API", - "keywords": [ - "api", - "client", - "instant", - "meilisearch", - "php", - "search" - ], - "support": { - "issues": "https://github.com/meilisearch/meilisearch-php/issues", - "source": "https://github.com/meilisearch/meilisearch-php/tree/v1.4.0" - }, - "time": "2023-09-25T11:42:54+00:00" - }, { "name": "microsoft/azure-storage-blob", "version": "1.5.4", @@ -5752,75 +6040,6 @@ ], "time": "2023-05-02T11:26:24+00:00" }, - { - "name": "php-http/client-common", - "version": "2.7.0", - "source": { - "type": "git", - "url": "https://github.com/php-http/client-common.git", - "reference": "880509727a447474d2a71b7d7fa5d268ddd3db4b" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/php-http/client-common/zipball/880509727a447474d2a71b7d7fa5d268ddd3db4b", - "reference": "880509727a447474d2a71b7d7fa5d268ddd3db4b", - "shasum": "" - }, - "require": { - "php": "^7.1 || ^8.0", - "php-http/httplug": "^2.0", - "php-http/message": "^1.6", - "psr/http-client": "^1.0", - "psr/http-factory": "^1.0", - "psr/http-message": "^1.0 || ^2.0", - "symfony/options-resolver": "~4.0.15 || ~4.1.9 || ^4.2.1 || ^5.0 || ^6.0", - "symfony/polyfill-php80": "^1.17" - }, - "require-dev": { - "doctrine/instantiator": "^1.1", - "guzzlehttp/psr7": "^1.4", - "nyholm/psr7": "^1.2", - "phpspec/phpspec": "^5.1 || ^6.3 || ^7.1", - "phpspec/prophecy": "^1.10.2", - "phpunit/phpunit": "^7.5.20 || ^8.5.33 || ^9.6.7" - }, - "suggest": { - "ext-json": "To detect JSON responses with the ContentTypePlugin", - "ext-libxml": "To detect XML responses with the ContentTypePlugin", - "php-http/cache-plugin": "PSR-6 Cache plugin", - "php-http/logger-plugin": "PSR-3 Logger plugin", - "php-http/stopwatch-plugin": "Symfony Stopwatch plugin" - }, - "type": "library", - "autoload": { - "psr-4": { - "Http\\Client\\Common\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Márk Sági-Kazár", - "email": "mark.sagikazar@gmail.com" - } - ], - "description": "Common HTTP Client implementations and tools for HTTPlug", - "homepage": "http://httplug.io", - "keywords": [ - "client", - "common", - "http", - "httplug" - ], - "support": { - "issues": "https://github.com/php-http/client-common/issues", - "source": "https://github.com/php-http/client-common/tree/2.7.0" - }, - "time": "2023-05-17T06:46:59+00:00" - }, { "name": "php-http/curl-client", "version": "2.3.0", @@ -5885,75 +6104,6 @@ }, "time": "2023-04-28T14:56:41+00:00" }, - { - "name": "php-http/message", - "version": "1.16.0", - "source": { - "type": "git", - "url": "https://github.com/php-http/message.git", - "reference": "47a14338bf4ebd67d317bf1144253d7db4ab55fd" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/php-http/message/zipball/47a14338bf4ebd67d317bf1144253d7db4ab55fd", - "reference": "47a14338bf4ebd67d317bf1144253d7db4ab55fd", - "shasum": "" - }, - "require": { - "clue/stream-filter": "^1.5", - "php": "^7.2 || ^8.0", - "psr/http-message": "^1.1 || ^2.0" - }, - "provide": { - "php-http/message-factory-implementation": "1.0" - }, - "require-dev": { - "ergebnis/composer-normalize": "^2.6", - "ext-zlib": "*", - "guzzlehttp/psr7": "^1.0 || ^2.0", - "laminas/laminas-diactoros": "^2.0 || ^3.0", - "php-http/message-factory": "^1.0.2", - "phpspec/phpspec": "^5.1 || ^6.3 || ^7.1", - "slim/slim": "^3.0" - }, - "suggest": { - "ext-zlib": "Used with compressor/decompressor streams", - "guzzlehttp/psr7": "Used with Guzzle PSR-7 Factories", - "laminas/laminas-diactoros": "Used with Diactoros Factories", - "slim/slim": "Used with Slim Framework PSR-7 implementation" - }, - "type": "library", - "autoload": { - "files": [ - "src/filters.php" - ], - "psr-4": { - "Http\\Message\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Márk Sági-Kazár", - "email": "mark.sagikazar@gmail.com" - } - ], - "description": "HTTP Message related tools", - "homepage": "http://php-http.org", - "keywords": [ - "http", - "message", - "psr-7" - ], - "support": { - "issues": "https://github.com/php-http/message/issues", - "source": "https://github.com/php-http/message/tree/1.16.0" - }, - "time": "2023-05-17T06:43:38+00:00" - }, { "name": "php-http/mock-client", "version": "1.6.0", @@ -6507,156 +6657,6 @@ ], "time": "2023-09-26T12:56:25+00:00" }, - { - "name": "symfony/options-resolver", - "version": "v6.3.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/options-resolver.git", - "reference": "a10f19f5198d589d5c33333cffe98dc9820332dd" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/options-resolver/zipball/a10f19f5198d589d5c33333cffe98dc9820332dd", - "reference": "a10f19f5198d589d5c33333cffe98dc9820332dd", - "shasum": "" - }, - "require": { - "php": ">=8.1", - "symfony/deprecation-contracts": "^2.5|^3" - }, - "type": "library", - "autoload": { - "psr-4": { - "Symfony\\Component\\OptionsResolver\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Provides an improved replacement for the array_replace PHP function", - "homepage": "https://symfony.com", - "keywords": [ - "config", - "configuration", - "options" - ], - "support": { - "source": "https://github.com/symfony/options-resolver/tree/v6.3.0" - }, - "funding": [ - { - "url": "https://symfony.com/sponsor", - "type": "custom" - }, - { - "url": "https://github.com/fabpot", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", - "type": "tidelift" - } - ], - "time": "2023-05-12T14:21:09+00:00" - }, - { - "name": "symfony/polyfill-php80", - "version": "v1.28.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/6caa57379c4aec19c0a12a38b59b26487dcfe4b5", - "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5", - "shasum": "" - }, - "require": { - "php": ">=7.1" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-main": "1.28-dev" - }, - "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" - } - }, - "autoload": { - "files": [ - "bootstrap.php" - ], - "psr-4": { - "Symfony\\Polyfill\\Php80\\": "" - }, - "classmap": [ - "Resources/stubs" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Ion Bazan", - "email": "ion.bazan@gmail.com" - }, - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "polyfill", - "portable", - "shim" - ], - "support": { - "source": "https://github.com/symfony/polyfill-php80/tree/v1.28.0" - }, - "funding": [ - { - "url": "https://symfony.com/sponsor", - "type": "custom" - }, - { - "url": "https://github.com/fabpot", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", - "type": "tidelift" - } - ], - "time": "2023-01-26T09:26:14+00:00" - }, { "name": "symfony/polyfill-uuid", "version": "v1.28.0", @@ -6895,6 +6895,7 @@ "prefer-lowest": false, "platform": { "php": "~8.1 || ~8.2", + "ext-bcmath": "*", "ext-dom": "*", "ext-hash": "*", "ext-json": "*", diff --git a/phpstan.neon b/phpstan.neon index 8d4013c9d..1685bed9b 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -21,6 +21,8 @@ parameters: - src/adapter/etl-adapter-xml/src - src/lib/array-dot/src - src/lib/doctrine-dbal-bulk/src + - src/lib/dremel/src + - src/lib/parquet/src excludePaths: - src/core/etl/src/Flow/ETL/Formatter/ASCII/ASCIITable.php @@ -32,5 +34,7 @@ parameters: - src/adapter/etl-adapter-elasticsearch/src/Flow/ETL/Adapter/Elasticsearch/ElasticsearchPHP/SearchResults.php - src/adapter/etl-adapter-elasticsearch/src/Flow/ETL/Adapter/Elasticsearch/ElasticsearchPHP/SearchParams.php - src/adapter/etl-adapter-elasticsearch/src/Flow/ETL/Adapter/Elasticsearch/ElasticsearchPHP/PointInTime.php + - src/lib/parquet/src/Flow/Parquet/Thrift/* + - src/lib/parquet/src/Flow/Parquet/BinaryReader/* tmpDir: var/phpstan/cache diff --git a/phpunit.xml b/phpunit.xml index 777ed373d..f2993252d 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -13,12 +13,15 @@ + src/core/etl/tests/Flow/ETL/Tests/Unit src/lib/array-dot/tests/Flow/ArrayDot/Tests/Unit src/lib/doctrine-dbal-bulk/tests/Flow/Doctrine/Bulk/Tests/Unit + src/lib/dremel/tests/Flow/Dremel/Tests/Unit + src/lib/parquet/tests/Flow/Parquet/Tests/Unit src/adapter/etl-adapter-amphp/tests/Flow/ETL/Async/Tests/Unit src/adapter/etl-adapter-avro/tests/Flow/ETL/Adapter/Avro/FlixTech/Tests/Unit src/adapter/etl-adapter-chartjs/tests/Flow/ETL/Adapter/ChartJS/Tests/Unit @@ -41,6 +44,7 @@ src/adapter/etl-adapter-text/tests/Flow/ETL/Adapter/Text/Tests/Integration src/adapter/etl-adapter-xml/tests/Flow/ETL/Tests/Integration src/adapter/etl-adapter-http/tests/Flow/ETL/Tests/Integration + src/lib/parquet/tests/Flow/Parquet/Tests/Integration src/lib/doctrine-dbal-bulk/tests/Flow/Doctrine/Bulk/Tests/Integration diff --git a/psalm.xml b/psalm.xml index f454fa651..866d3f90a 100644 --- a/psalm.xml +++ b/psalm.xml @@ -27,6 +27,8 @@ + + @@ -42,6 +44,9 @@ + + + diff --git a/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/Codename/ParquetExtractor.php b/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/Codename/ParquetExtractor.php index 5eeaf7a01..7a588ee20 100644 --- a/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/Codename/ParquetExtractor.php +++ b/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/Codename/ParquetExtractor.php @@ -12,6 +12,9 @@ use Flow\ETL\FlowContext; use Flow\ETL\Row; +/** + * @deprecated Use \Flow\ETL\Adapter\Parquet\ParquetExtractor instead + */ final class ParquetExtractor implements Extractor { /** diff --git a/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/ParquetExtractor.php b/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/ParquetExtractor.php new file mode 100644 index 000000000..38f869945 --- /dev/null +++ b/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/ParquetExtractor.php @@ -0,0 +1,78 @@ + $columns + */ + public function __construct( + private readonly Path $path, + private readonly Options $options, + private readonly ByteOrder $byteOrder = ByteOrder::LITTLE_ENDIAN, + private readonly array $columns = [], + private readonly int $rowsInBatch = 1000, + private readonly EntryFactory $entryFactory = new NativeEntryFactory() + ) { + } + + public function extract(FlowContext $context) : \Generator + { + foreach ($this->readers($context) as $fileData) { + $rows = []; + + foreach ($fileData['file']->values($this->columns) as $row) { + if ($context->config->shouldPutInputIntoRows()) { + $rows[] = \array_merge( + $row, + ['_input_file_uri' => $fileData['uri']] + ); + } else { + $rows[] = $row; + } + + if (\count($rows) >= $this->rowsInBatch) { + yield array_to_rows($rows, $this->entryFactory); + $rows = []; + } + } + + if (\count($rows)) { + yield array_to_rows($rows, $this->entryFactory); + } + } + } + + /** + * @psalm-suppress NullableReturnStatement + * + * @return \Generator + */ + private function readers(FlowContext $context) : \Generator + { + foreach ($context->streams()->fs()->scan($this->path, $context->partitionFilter()) as $filePath) { + yield [ + 'file' => (new Reader( + byteOrder: $this->byteOrder, + options: $this->options, + )) + ->readStream($context->streams()->fs()->open($filePath, Mode::READ)->resource()), + 'uri' => $filePath->uri(), + ]; + } + } +} diff --git a/src/adapter/etl-adapter-parquet/src/Flow/ETL/DSL/Parquet.php b/src/adapter/etl-adapter-parquet/src/Flow/ETL/DSL/Parquet.php index cd3d8ac5b..b427489a2 100644 --- a/src/adapter/etl-adapter-parquet/src/Flow/ETL/DSL/Parquet.php +++ b/src/adapter/etl-adapter-parquet/src/Flow/ETL/DSL/Parquet.php @@ -4,8 +4,8 @@ namespace Flow\ETL\DSL; -use Flow\ETL\Adapter\Parquet\Codename\ParquetExtractor; use Flow\ETL\Adapter\Parquet\Codename\ParquetLoader; +use Flow\ETL\Adapter\Parquet\ParquetExtractor; use Flow\ETL\Exception\MissingDependencyException; use Flow\ETL\Extractor; use Flow\ETL\Filesystem\Path; @@ -13,6 +13,8 @@ use Flow\ETL\Row\EntryFactory; use Flow\ETL\Row\Factory\NativeEntryFactory; use Flow\ETL\Row\Schema; +use Flow\Parquet\ByteOrder; +use Flow\Parquet\Options; /** * @infection-ignore-all @@ -29,6 +31,9 @@ class Parquet final public static function from( string|Path|array $uri, array $fields = [], + Options $options = new Options(), + ByteOrder $byte_order = ByteOrder::LITTLE_ENDIAN, + int $rows_in_batch = 1000, EntryFactory $entry_factory = new NativeEntryFactory() ) : Extractor { if (\is_array($uri)) { @@ -37,7 +42,10 @@ final public static function from( foreach ($uri as $filePath) { $extractors[] = new ParquetExtractor( $filePath, + $options, + $byte_order, $fields, + $rows_in_batch, $entry_factory ); } @@ -47,7 +55,10 @@ final public static function from( return new ParquetExtractor( \is_string($uri) ? Path::realpath($uri) : $uri, + $options, + $byte_order, $fields, + $rows_in_batch, $entry_factory ); } diff --git a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Integration/Codename/ParquetTest.php b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Integration/Codename/ParquetTest.php index f1f203f74..d918e1722 100644 --- a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Integration/Codename/ParquetTest.php +++ b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Integration/Codename/ParquetTest.php @@ -12,6 +12,8 @@ use Flow\ETL\Flow; use Flow\ETL\Row; use Flow\ETL\Rows; +use Flow\Parquet\Option; +use Flow\Parquet\Options; use PHPUnit\Framework\TestCase; final class ParquetTest extends TestCase @@ -94,7 +96,14 @@ public function test_writing_and_reading_parquet_with_all_supported_types() : vo $this->assertEquals( $rows, (new Flow()) - ->read(Parquet::from($path)) + ->read( + Parquet::from( + $path, + options: (new Options()) + ->set(Option::BYTE_ARRAY_TO_STRING) + ->set(Option::INT_96_AS_DATETIME) + ) + ) ->fetch() ); @@ -137,7 +146,12 @@ public function test_writing_safe_and_reading_parquet_with_all_supported_types() $this->assertEquals( $rows, (new Flow()) - ->read(Parquet::from($paths)) + ->read(Parquet::from( + $paths, + options: (new Options()) + ->set(Option::BYTE_ARRAY_TO_STRING) + ->set(Option::INT_96_AS_DATETIME) + )) ->sortBy(ref('integer')) ->fetch() ); diff --git a/src/core/etl/composer.json b/src/core/etl/composer.json index 58895c687..2a1485227 100644 --- a/src/core/etl/composer.json +++ b/src/core/etl/composer.json @@ -23,8 +23,7 @@ "league/flysystem-azure-blob-storage": "^3.0", "moneyphp/money": "^4", "ramsey/uuid": "^4.5", - "symfony/uid": "^6.3", - "symfony/validator": "^5.4 || ^6.2" + "symfony/uid": "^6.3" }, "config": { "optimize-autoloader": true, diff --git a/src/core/etl/src/Flow/ETL/Rows.php b/src/core/etl/src/Flow/ETL/Rows.php index 3bb9ba25c..5126aab1f 100644 --- a/src/core/etl/src/Flow/ETL/Rows.php +++ b/src/core/etl/src/Flow/ETL/Rows.php @@ -12,7 +12,9 @@ use Flow\ETL\Row\Comparator\NativeComparator; use Flow\ETL\Row\Entries; use Flow\ETL\Row\Entry\NullEntry; +use Flow\ETL\Row\EntryFactory; use Flow\ETL\Row\EntryReference; +use Flow\ETL\Row\Factory\NativeEntryFactory; use Flow\ETL\Row\Reference; use Flow\ETL\Row\References; use Flow\ETL\Row\Schema; @@ -36,6 +38,32 @@ public function __construct(Row ...$rows) $this->rows = \array_values($rows); } + public static function fromArray(array $data, EntryFactory $entryFactory = new NativeEntryFactory()) : self + { + /** @var array $rows */ + $rows = []; + + foreach ($data as $entries) { + if (!\is_array($entries)) { + throw new InvalidArgumentException('Rows expects nested array data structure: array>'); + } + + $row = []; + + /** + * @var string $entryName + * @var mixed $entryValue + */ + foreach ($entries as $entryName => $entryValue) { + $row[] = $entryFactory->create($entryName, $entryValue); + } + + $rows[] = Row::create(...$row); + } + + return new self(...$rows); + } + public function __serialize() : array { return [ diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/RowsTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/RowsTest.php index f54378846..4a094458f 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Unit/RowsTest.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/RowsTest.php @@ -163,6 +163,45 @@ public function test_array_access_unset() : void unset($rows[0]); } + public function test_building_rows_from_array() : void + { + $rows = Rows::fromArray( + [ + ['id' => 1234, 'deleted' => false, 'phase' => null], + ['id' => 4321, 'deleted' => true, 'phase' => 'launch'], + ] + ); + + $this->assertEquals( + new Rows( + Row::create( + Entry::integer('id', 1234), + Entry::bool('deleted', false), + Entry::null('phase'), + ), + Row::create( + Entry::integer('id', 4321), + Entry::bool('deleted', true), + Entry::string('phase', 'launch'), + ) + ), + $rows + ); + } + + public function test_building_rows_from_array_with_incorrect_structure() : void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Rows expects nested array data structure: array>'); + + Rows::fromArray( + [ + ['id' => 1234, 'deleted' => false, 'phase' => null], + 'string', + ] + ); + } + public function test_chunks_smaller_than_1() : void { $this->expectException(InvalidArgumentException::class); diff --git a/src/lib/dremel/.gitattributes b/src/lib/dremel/.gitattributes new file mode 100644 index 000000000..e02097205 --- /dev/null +++ b/src/lib/dremel/.gitattributes @@ -0,0 +1,9 @@ +*.php text eol=lf + +/.github export-ignore +/tests export-ignore + +/README.md export-ignore + +/.gitattributes export-ignore +/.gitignore export-ignore diff --git a/src/lib/dremel/.github/workflows/readonly.yaml b/src/lib/dremel/.github/workflows/readonly.yaml new file mode 100644 index 000000000..da596bcdd --- /dev/null +++ b/src/lib/dremel/.github/workflows/readonly.yaml @@ -0,0 +1,17 @@ +name: Readonly + +on: + pull_request_target: + types: [opened] + +jobs: + run: + runs-on: ubuntu-latest + steps: + - uses: superbrothers/close-pull-request@v3 + with: + comment: | + Hi, thank you for your contribution. + Unfortunately, this repository is read-only. It's a split from our main monorepo repository. + In order to proceed with this PR please open it against https://github.com/flow-php/flow repository. + Thank you. \ No newline at end of file diff --git a/src/lib/dremel/CONTRIBUTING.md b/src/lib/dremel/CONTRIBUTING.md new file mode 100644 index 000000000..a2d0671c7 --- /dev/null +++ b/src/lib/dremel/CONTRIBUTING.md @@ -0,0 +1,6 @@ +## Contributing + +This repo is **READ ONLY**, in order to contribute to Flow PHP project, please +open PR against [flow](https://github.com/flow-php/flow) monorepo. + +Changes merged to monorepo are automatically propagated into sub repositories. \ No newline at end of file diff --git a/src/lib/dremel/LICENSE b/src/lib/dremel/LICENSE new file mode 100644 index 000000000..da3e28da7 --- /dev/null +++ b/src/lib/dremel/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Flow PHP + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/lib/dremel/README.md b/src/lib/dremel/README.md new file mode 100644 index 000000000..8ffbb59d0 --- /dev/null +++ b/src/lib/dremel/README.md @@ -0,0 +1,7 @@ +# Dremel + +## Installation + +``` +composer require flow-php/dremel:1.x@dev +``` diff --git a/src/lib/dremel/composer.json b/src/lib/dremel/composer.json new file mode 100644 index 000000000..093b332b6 --- /dev/null +++ b/src/lib/dremel/composer.json @@ -0,0 +1,36 @@ +{ + "name": "flow-php/dremel", + "type": "library", + "description": "PHP ETL - Dremel algorithm implementation", + "keywords": [ + "etl", + "extract", + "transform", + "load", + "filter", + "array", + "dot" + ], + "require": { + "php": "~8.1 || ~8.2" + }, + "config": { + "optimize-autoloader": true, + "sort-packages": true + }, + "license": "MIT", + "autoload": { + "psr-4": { + "Flow\\": [ + "src/Flow" + ] + } + }, + "autoload-dev": { + "psr-4": { + "Flow\\": "tests/Flow" + } + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/src/lib/dremel/src/Flow/Dremel/Dremel.php b/src/lib/dremel/src/Flow/Dremel/Dremel.php new file mode 100644 index 000000000..bd04b775e --- /dev/null +++ b/src/lib/dremel/src/Flow/Dremel/Dremel.php @@ -0,0 +1,192 @@ + $repetitions + * @param array $definitions + * @param array $values + * + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress MixedAssignment + * @psalm-suppress ArgumentTypeCoercion + */ + public function assemble(array $repetitions, array $definitions, array $values) : \Generator + { + $this->assertInput($repetitions, $definitions); + + $output = []; + $maxDefinitionLevel = \max($definitions); + $maxRepetitionLevel = \count($repetitions) ? \max($repetitions) : 0; + + $valueIndex = 0; + + if ($maxRepetitionLevel === 0) { + foreach ($definitions as $definition) { + if ($definition === 0) { + yield null; + } elseif ($definition === $maxDefinitionLevel) { + yield $values[$valueIndex]; + $valueIndex++; + } + } + + return; + } + + $iteration = 0; + $stack = new Stack(); + + try { + foreach ($definitions as $definitionIndex => $definition) { + $repetition = $repetitions[$definitionIndex]; + + if ($repetition === 0) { + if ($stack->size()) { + yield $stack->dropFlat(); + $stack->clear(); + $stack->push(new ListNode($maxRepetitionLevel)); + } else { + $stack->push(new ListNode($maxRepetitionLevel)); + } + } + + if ($repetition === 0 && $definition === 0) { + yield null; + $stack->clear(); + } else { + if ($repetition <= $maxRepetitionLevel && $repetition > 0) { + /** @phpstan-ignore-next-line */ + $stack->last()->push( + $this->value($definition, $maxDefinitionLevel, $values, $valueIndex), + $repetition + ); + } elseif ($repetition === 0) { + /** @phpstan-ignore-next-line */ + $stack->last()->push( + $this->value($definition, $maxDefinitionLevel, $values, $valueIndex), + $maxRepetitionLevel + ); + } + } + + $this->debugDecodeNested($iteration, $repetition, $definition, $maxDefinitionLevel, $maxRepetitionLevel, $stack, $output); + $iteration++; + } + + if ($stack->size()) { + yield $stack->dropFlat(); + $stack->clear(); + } + } catch (\Throwable $e) { + $this->logger->error('[Dremel][Decode][Nested] error', [ + 'exception' => $e, + 'iteration' => $iteration, + 'repetition' => $repetitions, + 'definition' => $definitions, + 'values' => $values, + 'max_definition_level' => $maxDefinitionLevel, + 'max_repetition_level' => $maxRepetitionLevel, + ]); + + throw $e; + } + } + + public function shred() : void + { + throw new \RuntimeException('Not implemented'); + } + + /** + * @psalm-suppress MixedAssignment + */ + private function arrayTypeToString(?array $inputArray) : string + { + if ($inputArray === null) { + return 'null'; + } + + if (!\count($inputArray)) { + return ''; + } + + $result = []; + + foreach ($inputArray as $item) { + if (\is_array($item)) { + $result[] = '[' . $this->arrayTypeToString($item) . ']'; + } else { + if ($item === null) { + $result[] = 'null'; + } else { + $result[] = (string) $item; + } + } + } + + return \implode(', ', $result); + } + + private function assertInput(array $repetitions, array $definitions) : void + { + if (\count($repetitions) !== 0) { + if (\count(\array_unique([\count($repetitions), \count($definitions)])) !== 1) { + throw new InvalidArgumentException('repetitions, definitions and values count must be exactly the same'); + } + } + + if (\count($repetitions)) { + if ($repetitions[0] !== 0) { + throw new InvalidArgumentException('Repetitions must start with zero, otherwise it probably means that your data was split into multiple pages in which case proper reconstruction of rows is impossible.'); + } + } + } + + private function debugDecodeNested(int $iteration, ?int $repetition, int $definition, int $maxDefinitionLevel, int $maxRepetitionLevel, Stack $stack, array $output) : void + { + if ($this->logger instanceof NullLogger) { + return; + } + + $stackDebug = '[' . $this->arrayTypeToString($stack->__debugInfo()) . ']'; + $outputDebug = '[' . $this->arrayTypeToString($output) . ']'; + + $definitionDebug = $definition === $maxDefinitionLevel ? 'value' : 'null'; + + $this->logger->debug('[Dremel][Decode][Nested] data structure', [ + 'iteration' => $iteration, + 'repetition' => $repetition, + 'definition' => $definitionDebug, + 'max_definition_level' => $maxDefinitionLevel, + 'max_repetition_level' => $maxRepetitionLevel, + 'stack' => $stackDebug, + 'output' => $outputDebug, + ]); + } + + /** + * @psalm-suppress MixedAssignment + */ + private function value(int $definition, int $maxDefinitionLevel, array $values, int &$valueIndex) : mixed + { + if ($definition < $maxDefinitionLevel) { + return null; + } + + $value = $values[$valueIndex]; + $valueIndex++; + + return $value; + } +} diff --git a/src/lib/dremel/src/Flow/Dremel/Exception/InvalidArgumentException.php b/src/lib/dremel/src/Flow/Dremel/Exception/InvalidArgumentException.php new file mode 100644 index 000000000..c17e9dfd7 --- /dev/null +++ b/src/lib/dremel/src/Flow/Dremel/Exception/InvalidArgumentException.php @@ -0,0 +1,7 @@ +maxRepetitionLevel = $maxRepetitionLevel; + $this->value = $this->initializeList($maxRepetitionLevel); + $this->previousLevel = null; + } + + public function push(mixed $value, int $level) : self + { + if ($level > $this->maxRepetitionLevel) { + throw new \RuntimeException('Invalid level, max repetition level is ' . $this->maxRepetitionLevel . ' but ' . $level . ' was given'); + } + + if ($level === 0) { + throw new \RuntimeException('Invalid level, level must be greater than 0'); + } + + $this->pushToLevel($this->value, $value, $level, $level); + + $this->previousLevel = $level; + + return $this; + } + + public function value() : array + { + return $this->value; + } + + private function initializeList(int $level) : array + { + if ($level === 1) { + return []; + } + + return [$this->initializeList($level - 1)]; + } + + private function initializeListWithValue(int $level, mixed $value) : array + { + if ($level === 1) { + return [$value]; + } + + return [$this->initializeListWithValue($level - 1, $value)]; + } + + /** + * @psalm-suppress MixedArgument + * @psalm-suppress MixedAssignment + */ + private function pushToLevel(array &$array, mixed $value, int $level, int $nextLevel) : void + { + if ($nextLevel === 1) { + if ($this->previousLevel === null) { + $array[] = $value; + + return; + } + + if ($this->previousLevel > $level) { + $array[] = $this->initializeListWithValue($this->maxRepetitionLevel - $level, $value); + + return; + } + + if ($level === $this->maxRepetitionLevel) { + $array[] = $value; + + return; + } + + if ($level === $this->previousLevel) { + $array[] = $this->initializeListWithValue($this->maxRepetitionLevel - $this->previousLevel, $value); + + return; + } + + if ($this->previousLevel < $level) { + $array[] = $this->initializeListWithValue($this->maxRepetitionLevel - $level, $value); + + return; + } + + return; + } + + $this->pushToLevel($array[\count($array) - 1], $value, $level, $nextLevel - 1); + } +} diff --git a/src/lib/dremel/src/Flow/Dremel/Node.php b/src/lib/dremel/src/Flow/Dremel/Node.php new file mode 100644 index 000000000..a05d33099 --- /dev/null +++ b/src/lib/dremel/src/Flow/Dremel/Node.php @@ -0,0 +1,8 @@ +level; + } + + public function value() : array|null + { + return null; + } +} diff --git a/src/lib/dremel/src/Flow/Dremel/Stack.php b/src/lib/dremel/src/Flow/Dremel/Stack.php new file mode 100644 index 000000000..f5d840d17 --- /dev/null +++ b/src/lib/dremel/src/Flow/Dremel/Stack.php @@ -0,0 +1,84 @@ +nodes as $node) { + $output[] = $node->value(); + } + + return $output; + } + + public function clear() : void + { + $this->nodes = []; + } + + /** + * @psalm-suppress MixedAssignment + */ + public function dropFlat() : ?array + { + $output = []; + + if (\count($this->nodes) === 1) { + return $this->nodes[0]->value(); + } + + foreach ($this->nodes as $node) { + $output[] = $node->value(); + } + + $this->nodes = []; + + return $output; + } + + public function last() : Node + { + if (\count($this->nodes) === 0) { + throw new RuntimeException('Stack is empty'); + } + + return $this->nodes[\count($this->nodes) - 1]; + } + + public function pop() : Node + { + if (\count($this->nodes) === 0) { + throw new RuntimeException('Stack is empty'); + } + + return \array_pop($this->nodes); + } + + public function push(Node $node) : void + { + $this->nodes[] = $node; + } + + public function size() : int + { + return \count($this->nodes); + } +} diff --git a/src/lib/dremel/tests/Flow/Dremel/Tests/Unit/DremelTest.php b/src/lib/dremel/tests/Flow/Dremel/Tests/Unit/DremelTest.php new file mode 100644 index 000000000..e43dca113 --- /dev/null +++ b/src/lib/dremel/tests/Flow/Dremel/Tests/Unit/DremelTest.php @@ -0,0 +1,351 @@ +assertSame( + [[3, 7, 5], [4, 4, 7], [10, 6, 4], [10, 3, 2], [10, 4, 4], [5, 3, 2], [1, 4, 3], [4, 3, 9], [10, 3, 4], [5, 7, 4]], + \iterator_to_array((new Dremel())->assemble($repetitions, $definitions, $values)) + ); + } + + public function test_decode_flat_column_of_integers_where_every_second_one_is_null() : void + { + $repetitions = []; + $definitions = [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]; + $values = [0, 2, 4, 6, 8, null, null, null, null, null]; + + $this->assertSame( + [0, null, 2, null, 4, null, 6, null, 8, null], + \iterator_to_array((new Dremel())->assemble($repetitions, $definitions, $values)) + ); + } + + public function test_decode_flat_column_of_integers_without_nulls() : void + { + $repetitions = []; + $definitions = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; + $values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + + $this->assertSame( + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + \iterator_to_array((new Dremel())->assemble($repetitions, $definitions, $values)) + ); + } + + public function test_decode_list_with_nulls_and_different_size_of_each_list() : void + { + $repetitions = [0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1]; + $definitions = [3, 3, 2, 2, 3, 3, 2, 3, 3, 2, 2, 2, 2, 3, 3, 2, 2, 3, 2, 2, 3, 2]; + $values = [10, 7, 9, 8, 9, 4, 6, 3, 10, 8]; + + $this->assertSame( + [[10], [7, null, null], [9], [8, null], [9], [4, null, null, null, null], [6], [3, null, null], [10, null, null], [8, null]], + \iterator_to_array((new Dremel())->assemble($repetitions, $definitions, $values)) + ); + } + + public function test_decode_nested_list_v2() : void + { + $repetitions = [0, 3, 3, 2, 3, 3, 1, 3, 2, 3, 2, 3, 3, 1, 3, 0, 3, 3, 2, 3, 3, 2, 3, 3, 1, 3, 2, 1, 3, 3, 2, 3, 3, 0, 3, 3, 1, 3, 2, 1, 3, 2, 2, 3, 0, 3, 3, 2, 3, 2, 3, 3, 0, 3, 3, 0, 1, 3, 2, 3, 1, 3, 3, 2, 3, 0, 2, 3, 3, 2, 1, 2, 3, 0, 3, 3, 2, 3, 3, 0, 3, 3, 2, 2, 3, 1, 2, 3, 0, 1, 0, 3, 1, 3, 1, 3, 3, 2, 0, 3, 2, 3, 3, 1, 3, 0, 2, 3, 1, 3, 2, 2, 0, 2, 3, 1, 2, 3, 3, 1, 3, 3, 2, 3, 0, 3, 0, 3, 3, 2, 3, 3, 1, 3, 3, 2, 2, 3, 3, 0, 2, 1, 3, 2, 2, 0, 3, 3, 1, 3, 2, 2, 1, 3, 3, 0, 3, 3, 1, 3, 3, 2, 3, 3, 2, 3, 3, 1, 3, 2, 0, 3, 2, 3, 3, 2, 3, 1, 3, 3, 2, 3, 3, 1, 2, 0, 3, 2, 3, 2, 3, 1, 1, 3, 3, 2, 3, 3, 2, 0, 3, 0, 2, 0, 3, 1, 3, 3, 1, 2, 0,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 9, 3, 1, 7, 6, 4, 4, 5, 6, 5, 2, 5, 10, 10, 9, 10, 2, 8, 2, 2, 2, 10, 5, 10, 3, 2, 8, 6, 8, 4, 9, 9, 6, 5, 5, 4, 1, 1, 5, 3, 9, 6, 6, 5, 9, 3, 10, 6, 1, 5, 6, 6, 7, 1, 7, 5, 5, 7, 2, 10, 1, 8, 8, 3, 4, 3, 5, 2, 1, 3, 4, 2, 1, 2, 10, 4, 5, 1, 6, 7, 5, 3, 5, 10, 7, 6, 2, 8, 10, 4, 2, 2, 1, 4, 5, 3, 2, 3, 2, 2, 3, 2, 6, 3, 5, 9, 8, 8, 5, 7, 5, 5, 4, 7, 4, 10, 5, 9, 5, 5, 1, 6, 3, 5, 10, 9, 7, 9, 9, 9, 3, 4, 7, 3, 4, 3, 5, 9, 3, 4, 8, 4, 4, 10, 3, 1, 7, 7, 1, 1, 2, 1, 6, 5, 7, 3, 9, 5, 6, 1, 4, 8, 7]; + + $this->assertSame( + [ + [[[5, 3, 8], [2, 9, 5]], [[5, 10], [9, 7], [2, 1, 8]], [[2, 4]]], + [[[7, 2, 4], [4, 10, 6], [5, 6, 6]], [[3, 6], [5]], [[7, 2, 10], [6, 4, 7]]], + [[[2, 8, 10]], [[6, 5], [9]], [[2, 10], [3], [7, 3]]], + [[[7, 8, 7], [5, 8], [4, 1, 5]]], + [[[1, 10, 7]]], + [[[4]], [[7, 2], [7, 3]], [[9, 3, 2], [3, 9]]], + [[[5], [2, 6, 2], [10]], [[10], [7, 9]]], + [[[9, 8, 5], [9, 7, 7]]], + [[[9, 1, 8], [2], [9, 10]], [[6], [2, 10]]], + [[[10]], [[3]]], + [[[5, 6]], [[5, 10]], [[6, 3, 6], [8]]], + [[[5, 1], [10, 2, 10]], [[4, 4]]], + [[[5], [6, 9]], [[5, 6], [3], [4]]], + [[[3], [9, 10]], [[3], [2, 1, 2]], [[6, 7, 3], [6, 1]]], + [[[7, 6]]], + [[[2, 2, 10], [5, 1, 6]], [[3, 5, 3], [5], [6, 2, 8]]], + [[[3], [5]], [[8, 1], [7], [9]]], + [[[4, 7, 6]], [[7, 8], [8], [1]], [[4, 7, 3]]], + [[[6, 5, 6]], [[7, 9, 8], [2, 4, 9], [8, 6, 6]], [[5, 2], [6]]], + [[[1, 10], [6, 1, 1], [6, 7]], [[1, 5, 2], [1, 9, 1]], [[7], [10]]], + [[[5, 2], [1, 8], [7, 9]], [[1]], [[2, 8, 10], [7, 9, 5], [9]]], + [[[5, 2]]], + [[[1], [5]]], + [[[5, 3]], [[5, 6, 6]], [[6], [1]]], + [[[1]], [[4], [3, 8, 3]]], + [[[9, 3, 4]], [[7, 2, 9], [6, 10], [5, 5, 9]], [[9, 9, 7]]], + [[[1, 1, 8], [10]], [[6, 4]]], + [[[7, 7, 10]]], + [[[9, 10], [8]], [[10, 3, 2], [5], [2, 1]], [[9, 2], [9, 6]]], + [[[7], [7]], [[3, 7], [9, 4, 8], [3, 1]]], + [[[4, 6], [1]]], + [[[3], [2, 4], [5, 7, 1]], [[9, 9, 10], [4]]], + [[[2, 5]]], + [[[8, 9, 2]], [[7], [1, 4]]], + [[[9, 1, 9]], [[9, 2], [4, 4, 7]], [[7], [2, 9], [3, 4]]], + [[[4, 1]], [[9, 4, 1], [1], [8, 1]], [[1, 7, 3], [10, 3, 8]]], + [[[3, 10, 10], [5, 2]], [[6], [8]], [[1, 2, 9], [9, 8]]], + [[[10]], [[10, 10, 5], [1, 1], [8, 9]]], + [[[1, 5], [9], [7, 3]], [[5, 9, 8], [8, 6]]], + [[[2], [8]]], + [[[8, 4, 5]], [[1, 10], [7, 9, 5]], [[10], [2], [2, 7]]], + [[[1, 7], [2, 6, 10]], [[7, 6, 5]], [[7], [4, 3]]], + [[[4]], [[10, 10, 7], [9]]], + [[[9, 4]], [[5, 5]]], + [[[6, 10], [1], [1, 3, 10]]], + [[[5], [10, 5]]], + [[[2, 2, 8], [7, 4, 9]]], + [[[7, 4, 1]]], + [[[1], [6, 3, 10], [1, 6]], [[3, 10], [5], [8]], [[2, 5, 9], [3, 9, 3], [9]]], + [[[1, 8, 4], [6, 6]], [[7, 9, 2]]], + [[[8]], [[3, 3, 5], [2, 10]], [[4], [3, 8, 1], [6]]], + [[[6, 7, 1], [9, 10]], [[7]], [[4, 7, 2], [3, 6, 10], [5, 8]]], + [[[4, 7, 9]], [[4, 3, 4], [7, 10, 10]], [[3, 4], [2, 1]]], + [[[6, 10], [7, 10]], [[1]]], + [[[9, 10, 5], [8]]], + [[[9, 10], [1, 9], [8]]], + [[[7, 1, 4]], [[1, 3, 6]]], + [[[10]], [[8]], [[9], [6, 1, 7]]], + [[[2, 10]], [[6, 7], [3], [7, 9]], [[6, 3], [1]]], + [[[6, 9], [4, 6, 7], [9, 7]], [[7, 3, 4], [3, 3, 9], [5, 5]], [[2, 8], [5]]], + [[[10, 10, 8], [2, 9, 6]], [[2, 5]], [[2]]], + [[[9, 4], [9, 3, 3], [4]], [[9], [8], [2]]], + [[[2], [6, 10], [9, 3]], [[1], [3], [8]], [[8, 9, 6], [8, 8, 1], [1, 2, 4]]], + [[[1]]], + [[[4, 4, 9]], [[5, 7], [1, 6], [1, 7]]], + [[[3, 5, 5], [7, 2]], [[3, 10, 10], [3, 7]], [[6, 2], [10]]], + [[[3, 10], [2], [7]]], + [[[9, 3], [2], [2, 8, 10]], [[2]]], + [[[10]], [[4, 4]]], + [[[4, 10, 9], [8, 10]], [[2, 9], [10, 1, 7], [10, 3, 4]]], + [[[3, 9, 5], [8, 10]]], + [[[9, 5, 5], [3, 4, 3]]], + [[[6, 6, 9], [8, 1], [9]]], + [[[2], [3, 9]], [[4, 3], [8], [9, 6]], [[9, 10]]], + [[[9, 8, 4], [8]], [[7], [2, 2, 6]], [[7], [6]]], + [[[4, 4]], [[7, 3, 2], [5, 7]]], + [[[9, 10], [8, 6, 8]], [[3, 4]]], + [[[9], [3, 1, 7]]], + [[[6], [4]], [[4, 5, 6], [5, 2], [5]]], + [[[10], [10, 9], [10, 2]], [[8], [2, 2, 2]]], + [[[10], [5]], [[10], [3], [2, 8]], [[6]]], + [[[8, 4, 9], [9, 6, 5], [5, 4, 1]]], + [[[1, 5, 3]], [[9], [6, 6], [5]], [[9, 3], [10], [6, 1]]], + [[[5]]], [[[6], [6, 7], [1, 7]]], + [[[5, 5], [7]], [[2, 10]], [[1], [8], [8, 3, 4]]], + [[[3, 5, 2]], [[1, 3, 4], [2, 1, 2]]], + [[[10, 4, 5], [1, 6, 7]], [[5]], [[3, 5, 10], [7, 6, 2]]], + [[[8, 10]], [[4], [2, 2]]], + [[[1], [4, 5, 3]], [[2, 3]]], + [[[2, 2], [3, 2]], [[6, 3, 5]], [[9], [8, 8, 5]]], + [[[7, 5], [5, 4]]], + [[[7, 4]], [[10, 5, 9]]], + [[[5, 5], [1]]], + [[[6, 3, 5]]], + [[[10], [9, 7, 9], [9]]], + [[[9, 3], [4, 7], [3, 4]], [[3]]], + [[[5], [9, 3, 4]]], + [[[8, 4, 4], [10]], [[3, 1, 7], [7], [1, 1]], [[2], [1]]], + [[[6, 5], [7, 3], [9]], [[5, 6, 1]], [[4, 8], [7]]], + ], + \iterator_to_array((new Dremel())->assemble($repetitions, $definitions, $values)) + ); + } + + public function test_decode_nullable_column_of_integer_list() : void + { + $repetitions = [0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0]; + $definitions = [3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0]; + $values = [5, 9, 2, 3, 2, 9, 5, 2, 3, 7, 2, 3, 2, 6, 6, null, null, null, null, null]; + + $this->assertSame( + [[5, 9, 2], null, [3, 2, 9], null, [5, 2, 3], null, [7, 2, 3], null, [2, 6, 6], null], + \iterator_to_array((new Dremel())->assemble($repetitions, $definitions, $values)) + ); + } + + public function test_decode_when_repetitions_definitions_and_values_does_not_have_them_same_number_of_elements() : void + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('repetitions, definitions and values count must be exactly the same'); + + \iterator_to_array((new Dremel())->assemble([1, 2], [1], [1, 2])); + } + + public function test_decoding_nested_list_with_nulls_and_different_size_of_each_list() : void + { + $repetitions = [0, 2, 1, 2, 0, 2, 2, 1, 2, 2, 0, 2, 2, 1, 2, 2, 1, 2, 2, 0, 2, 2, 1, 2, 2, 0, 2, 2, 2, 1, 2, 2, 2, 0, 2, 1, 2, 1, 2, 1, 2, 0, 2, 1, 2, 0, 2, 1, 2, 1, 2, 1, 2, 0, 2, 1, 2, 0, 2, 2, 1, 2, 2, 1, 2, 2]; + $definitions = [5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 4, 5, 5, 4, 5, 4, 4, 5, 5, 5, 5, 4, 4, 5, 4, 5, 5, 5, 5, 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 4, 5, 4, 4, 4, 5, 5, 4, 4, 5]; + $values = [9, 5, 9, 6, 6, 7, 7, 9, 3, 10, 4, 4, 5, 4, 6, 9, 10, 9, 6, 3, 3, 8, 7, 10, 4, 3, 8, 2, 8, 3, 6, 10, 4, 5, 4, 5, 2, 10, 5, 1, 2, 2, 3, 9, 9, 9, 9, 9]; + + /** + * stack: [] + * current_list: null. + * + * iteration 0: stack[], current_list[9] - rep 0, def 5 (take next val) + * iteration 1: stack[], current_list[9, 5] - rep 2, def 5 (take next val) + * iteration 2: stack[[[9, 5]]], current_list[9] - rep 1 def 5 (take next val) + * iteration 3: stack[[[9, 5]]], current_list[9, null] - rep 2 def 4 (take null) + * iteration 4: stack[[[9, 5], [9, null]]], current_list[6] - rep 0 def 5 (take next val) + * iteration 5: stack[[[9, 5], [9, null]]], current_list[6,6] - rep 2 def 5 (take next val) + * iteration 6: stack[[[9, 5], [9, null]]], current_list[6,6,7] - rep 2 def 5 (take next val) + * iteration 7: stack[[[9, 5], [9, null]], [[6,6,7]], current_list[7] - rep 1 def 5 (take next val) + */ + $this->assertSame( + [ + [[9, 5], [9, null]], + [[6, 6, 7], [7, 9, 3]], + [[10, 4, 4], [5, 4, null], [6, 9, 10]], + [[9, null, null], [6, 3, 3]], + [[8, 7, null, 10], [4, null, 3, null]], + [[null, 8], [2, 8], [3, null], [null, 6]], + [[null, 10], [4, 5]], + [[4, null], [null, null], [5, 2], [10, null]], + [[null, 5], [1, null]], + [[2, null, null], [null, 2, 3], [null, null, 9]], + ], + \iterator_to_array((new Dremel())->assemble($repetitions, $definitions, $values)) + ); + } + + public function test_decoding_nested_list_with_nulls_and_different_size_of_each_list_and_deep_nesting() : void + { + $repetitions = [0, 3, 2, 3, 2, 3, 2, 3, 1, 3, 2, 3, 2, 3, 2, 3, 1, 3, 2, 3, 2, 3, 2, 3, 1, 3, 2, 3, 2, 3, 2, 3, 0, 3, 3, 2, 3, 3, 2, 3, 3, 2, 3, 3, 1, 3, 3, 2, 3, 3, 2, 3, 3, 2, 3, 3, 0, 3, 3, 3, 2, 3, 3, 3, 1, 3, 3, 3, 2, 3, 3, 3, 1, 3, 3, 3, 2, 3, 3, 3, 1, 3, 3, 3, 2, 3, 3, 3, 0, 3, 3, 2, 3, 3, 2, 3, 3, 1, 3, 3, 2, 3, 3, 2, 3, 3, 0, 3, 2, 3, 1, 3, 2, 3, 1, 3, 2, 3, 0, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 1, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 0, 3, 3, 2, 3, 3, 2, 3, 3, 2, 3, 3, 1, 3, 3, 2, 3, 3, 2, 3, 3, 2, 3, 3, 0, 3, 2, 3, 2, 3, 1, 3, 2, 3, 2, 3, 1, 3, 2, 3, 2, 3, 1, 3, 2, 3, 2, 3, 0, 3, 3, 2, 3, 3, 2, 3, 3, 1, 3, 3, 2, 3, 3, 2, 3, 3, 1, 3, 3, 2, 3, 3, 2, 3, 3, 0, 3, 3, 3, 2, 3, 3, 3, 1, 3, 3,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1, 8, 3, 8, 7, 9, 5, 9, 8, 3, 6, 3, 10, 10, 10, 6, 8, 7, 2, 1, 6, 2, 4, 4, 1, 7, 2, 1, 7, 8, 9, 3, 9, 4, 8, 4, 10, 9, 5, 9, 2, 1, 6, 9, 3, 6, 10, 4, 5, 9, 10, 8, 3, 3, 9, 7, 10, 9, 4, 10, 5, 1, 2, 7, 6, 10, 2, 5, 7, 5, 3, 9, 10, 1, 5, 7, 6, 7, 4, 4, 6, 7, 7, 6, 3, 6, 1, 8, 2, 8, 3, 7, 9, 3, 5, 8, 5, 2, 2, 5]; + + /** + * stack: [] + * current_list: null. + * + * iteration 0: stack[], current_list[10] - rep 0, def 7 (take next val) + * iteration 1: stack[], current_list[10, 5] - rep 3, def 7 (take next val) + * iteration 2: stack[], current_list[[10, 5], [9]] - rep 2 def 7 (take next val) + * iteration 3: stack[], current_list[[10, 5], [9, null]] - rep 3 def 6 (take null) + */ + $this->assertSame( + [ + [[[10, 5], [9, null], [1, 10], [7, null]], [[null, 6], [3, 1], [null, 6], [9, 9]], [[null, 4], [null, 6], [null, null], [3, 8]], [[5, 8], [1, 10], [null, null], [9, 4]]], + [[[null, 6, null], [2, null, null], [8, 4, 6], [null, 8, 9]], [[null, 4, 10], [null, null, null], [4, null, null], [8, 4, 3]]], + [[[9, 2, 10, null], [8, 5, 2, 7]], [[null, 8, 7, 10], [3, null, null, 8]], [[1, 5, 10, 6], [null, 5, 6, 1]], [[6, 5, 6, 7], [1, 6, null, 10]]], + [[[7, 8, 2], [8, 2, null], [7, null, 7]], [[8, 7, 3], [9, 2, null], [3, null, null]]], + [[[null, 10], [1, 8]], [[3, 8], [7, 9]], [[5, null], [9, null]]], + [[[null, 8, null, 3], [null, null, 6, null], [3, null, 10, 10], [null, 10, 6, 8]], [[7, 2, 1, 6], [2, 4, null, null], [4, 1, null, 7], [2, 1, 7, 8]]], + [[[9, null, 3], [9, 4, 8], [null, 4, 10], [9, null, 5]], [[9, 2, 1], [6, 9, null], [3, 6, 10], [4, null, null]]], + [[[5, 9], [10, null], [null, 8]], [[3, null], [null, 3], [null, null]], [[null, null], [9, null], [7, 10]], [[9, null], [4, 10], [5, 1]]], + [[[2, 7, 6], [10, 2, null], [null, null, null]], [[5, 7, 5], [null, null, 3], [9, 10, 1]], [[null, 5, 7], [null, null, 6], [7, 4, 4]]], + [[[6, 7, 7, 6], [3, 6, 1, 8]], [[2, 8, 3, null], [7, 9, 3, 5]], [[8, 5, null, 2], [null, 2, 5, null]]], + ], + \iterator_to_array((new Dremel())->assemble($repetitions, $definitions, $values)) + ); + } + + public function test_reconstructing_map() : void + { + $repetitions = [0, 4, 4, 1, 4, 3, 2, 4, 3, 4, 3, 4, 2, 1, 2, 4, 4, 3, 4, 0, 4, 2, 4, 4, 2, 4, 4, 3, 1, 4, 3, 4, 4, 2, 4, 4, 2, 1, 4, 2, 4, 4, 2, 3, 4, 4]; + $definitions = [11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11]; + $values = [6, 10, 10, 5, 9, 8, 4, 7, 4, 7, 1, 6, 6, 10, 6, 6, 1, 5, 8, 5, 2, 6, 3, 9, 9, 10, 7, 9, 4, 6, 5, 10, 3, 5, 4, 7, 6, 3, 5, 7, 5, 2, 8, 3, 8, 5]; + + $this->assertSame( + [ + [ + [ + [ + [6, 10, 10], + ], + ], + [ + [ + [5, 9], + [8], + ], + [ + [4, 7], + [4, 7], + [1, 6], + ], + [ + [6], + ], + ], + [ + [ + [10], + ], + [ + [6, 6, 1], + [5, 8], + ], + ], + ], + [ + [ + [ + [5, 2], + ], + [ + [6, 3, 9], + ], + [ + [9, 10, 7], + [9], + ], + ], + [ + [ + [4, 6], + [5, 10, 3], + ], + [ + [5, 4, 7], + ], + [ + [6], + ], + ], + [ + [ + [3, 5], + ], + [ + [7, 5, 2], + ], + [ + [8], + [3, 8, 5], + ], + ], + ], + ], + \iterator_to_array((new Dremel())->assemble($repetitions, $definitions, $values)) + ); + } + + public function test_starting_repetitions_with_1() : void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Repetitions must start with zero, otherwise it probably means that your data was split into multiple pages in which case proper reconstruction of rows is impossible.'); + + $repetitions = [1, 0, 0, 1, 0, 1]; + $definitions = [4, 4, 4, 4, 4, 4]; + $values = ['value', 'value', 'value', 'value', 'value', 'value']; + + \iterator_to_array((new Dremel())->assemble($repetitions, $definitions, $values)); + } +} diff --git a/src/lib/dremel/tests/Flow/Dremel/Tests/Unit/ListNodeTest.php b/src/lib/dremel/tests/Flow/Dremel/Tests/Unit/ListNodeTest.php new file mode 100644 index 000000000..554389e4d --- /dev/null +++ b/src/lib/dremel/tests/Flow/Dremel/Tests/Unit/ListNodeTest.php @@ -0,0 +1,214 @@ +assertsame( + [[[]]], + (new ListNode(3))->value() + ); + } + + public function test_push_by_2_levels() : void + { + $this->assertSame( + [ + [ + [ + [1], + ], + [ + [2], + ], + ], + [ + [ + [3], + ], + [ + [4, 5], + ], + ], + ], + (new ListNode(4)) + ->push(1, level: 4) + ->push(2, level: 2) + ->push(3, level: 1) + ->push(4, level: 2) + ->push(5, level: 4) + ->value(), + ); + } + + public function test_push_to_level_3_then_2_then_1() : void + { + $this->assertSame( + [ + [ + [ + 0 => 1, + ], + [ + 0 => 2, + ], + ], + [ + [ + 0 => 3, + ], + ], + ], + (new ListNode(3))->push(1, 3)->push(2, 2)->push(3, 1)->value(), + ); + } + + public function test_push_to_level_3_then_2_then_1_then_1_again() : void + { + $this->assertSame( + [ + [ + [ + 0 => 1, + ], + [ + 0 => 2, + ], + ], + [ + [ + 0 => 3, + ], + ], + [ + [ + 0 => 4, + ], + ], + ], + (new ListNode(3))->push(1, 3)->push(2, 2)->push(3, 1)->push(4, 1)->value(), + ); + } + + public function test_push_to_level_3_then_2_then_1_then_2() : void + { + $this->assertSame( + [ + [ + [ + 0 => 1, + ], + [ + 0 => 2, + ], + ], + [ + [ + 0 => 3, + ], + [ + 0 => 4, + ], + ], + ], + (new ListNode(3))->push(1, 3)->push(2, 2)->push(3, 1)->push(4, 2)->value(), + ); + } + + public function test_push_to_level_3_then_2_then_1_then_3() : void + { + $this->assertSame( + [ + [ + [ + 0 => 1, + ], + [ + 0 => 2, + ], + ], + [ + [ + 0 => 3, + 1 => 4, + ], + ], + ], + (new ListNode(3))->push(1, 3)->push(2, 2)->push(3, 1)->push(4, 3)->value(), + ); + } + + public function test_push_value_highest_level_then_lower_and_higher() : void + { + $this->assertSame( + [ + [ + [ + 0 => 1, + ], + [ + 0 => 2, + ], + [ + 0 => 3, + ], + ], + ], + (new ListNode(3))->push(1, 3)->push(2, 2)->push(3, 2)->value(), + ); + } + + public function test_push_value_to_highest_level() : void + { + $this->assertSame( + [ + [ + [ + 0 => 1, + ], + [ + 0 => 2, + 1 => 3, + ], + ], + ], + (new ListNode(3))->push(value: 1, level: 3)->push(value: 2, level: 2)->push(value: 3, level: 3)->value(), + ); + } + + public function test_push_value_to_lower_level() : void + { + $this->assertSame( + [ + [ + [ + 0 => 1, + ], + [ + 0 => 2, + ], + ], + ], + (new ListNode(3))->push(value: 1, level: 3)->push(value: 2, level: 2)->value(), + ); + } + + public function test_push_value_to_specific_level() : void + { + $this->assertSame( + [ + [ + [ + 0 => 1, + ], + ], + ], + (new ListNode(3))->push(value: 1, level: 3)->value(), + ); + } +} diff --git a/src/lib/parquet/.gitattributes b/src/lib/parquet/.gitattributes new file mode 100644 index 000000000..73fb913a0 --- /dev/null +++ b/src/lib/parquet/.gitattributes @@ -0,0 +1,10 @@ +*.php text eol=lf + +/.github export-ignore +/tests export-ignore +/resource export-ignore + +/README.md export-ignore + +/.gitattributes export-ignore +/.gitignore export-ignore diff --git a/src/lib/parquet/.github/workflows/readonly.yaml b/src/lib/parquet/.github/workflows/readonly.yaml new file mode 100644 index 000000000..da596bcdd --- /dev/null +++ b/src/lib/parquet/.github/workflows/readonly.yaml @@ -0,0 +1,17 @@ +name: Readonly + +on: + pull_request_target: + types: [opened] + +jobs: + run: + runs-on: ubuntu-latest + steps: + - uses: superbrothers/close-pull-request@v3 + with: + comment: | + Hi, thank you for your contribution. + Unfortunately, this repository is read-only. It's a split from our main monorepo repository. + In order to proceed with this PR please open it against https://github.com/flow-php/flow repository. + Thank you. \ No newline at end of file diff --git a/src/lib/parquet/CONTRIBUTING.md b/src/lib/parquet/CONTRIBUTING.md new file mode 100644 index 000000000..a2d0671c7 --- /dev/null +++ b/src/lib/parquet/CONTRIBUTING.md @@ -0,0 +1,6 @@ +## Contributing + +This repo is **READ ONLY**, in order to contribute to Flow PHP project, please +open PR against [flow](https://github.com/flow-php/flow) monorepo. + +Changes merged to monorepo are automatically propagated into sub repositories. \ No newline at end of file diff --git a/src/lib/parquet/LICENSE b/src/lib/parquet/LICENSE new file mode 100644 index 000000000..da3e28da7 --- /dev/null +++ b/src/lib/parquet/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Flow PHP + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/lib/parquet/README.md b/src/lib/parquet/README.md new file mode 100644 index 000000000..3322e1481 --- /dev/null +++ b/src/lib/parquet/README.md @@ -0,0 +1,7 @@ +# Parquet + +## Installation + +``` +composer require flow-php/parquet:1.x@dev +``` diff --git a/src/lib/parquet/composer.json b/src/lib/parquet/composer.json new file mode 100644 index 000000000..c63e347d7 --- /dev/null +++ b/src/lib/parquet/composer.json @@ -0,0 +1,40 @@ +{ + "name": "flow-php/parquet", + "type": "library", + "description": "PHP ETL - library for reading and writing Parquet files", + "keywords": [ + "etl", + "extract", + "transform", + "load", + "filter", + "array", + "dot" + ], + "require": { + "php": "~8.1 || ~8.2", + "ext-bcmath": "*" + }, + "config": { + "optimize-autoloader": true, + "sort-packages": true + }, + "license": "MIT", + "autoload": { + "psr-4": { + "Flow\\": [ + "src/Flow" + ] + }, + "files": [ + "src/Flow/Parquet/functions.php" + ] + }, + "autoload-dev": { + "psr-4": { + "Flow\\": "tests/Flow" + } + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/src/lib/parquet/resources/python/.gitignore b/src/lib/parquet/resources/python/.gitignore new file mode 100644 index 000000000..857d7e89c --- /dev/null +++ b/src/lib/parquet/resources/python/.gitignore @@ -0,0 +1,3 @@ +output +!output/.gitkeep +parquet \ No newline at end of file diff --git a/src/lib/parquet/resources/python/README.md b/src/lib/parquet/resources/python/README.md new file mode 100644 index 000000000..29b14fce1 --- /dev/null +++ b/src/lib/parquet/resources/python/README.md @@ -0,0 +1,27 @@ +# Test Data Generators + +This directory contains scripts to generate test data for the Flwo PHP Parquet reader/writer. + +### Prerequisites + - Python 3.x installed + - pip installed (Python Package Index) + +### Installation + +First go to the `src/lib/parquet/resources/python` directory and run the following command to install the required dependencies: + +```shell +python3 -m venv parquet +source parquet/bin/activate +pip install -r requirements.txt +``` + +Once all dependencies are installed, you can run the following command to generate the test data: + +```shell +python generators/lists.py +python generators/maps.py +python generators/orders.py +python generators/primitives.py +python generators/structs.py +``` \ No newline at end of file diff --git a/src/lib/parquet/resources/python/generators/lists.py b/src/lib/parquet/resources/python/generators/lists.py new file mode 100644 index 000000000..c88a97fb0 --- /dev/null +++ b/src/lib/parquet/resources/python/generators/lists.py @@ -0,0 +1,78 @@ +import pandas as pd +import random +import os +import pyarrow as pa +import pyarrow.parquet as pq + +# Number of rows to generate +n_rows = 100 + +# Functions to generate the data +def generate_list_nested(): + return [ + [ + [ + random.randint(1, 10) for _ in range(random.randint(1, 3)) + ] for _ in range(random.randint(1, 3)) + ] for _ in range(random.randint(1, 3)) + ] + +# Columns +list_col = pd.Series([[random.randint(1, 10) for _ in range(3)] for _ in range(n_rows)], dtype='object') +list_nullable_col = pd.Series([[random.randint(1, 10) for _ in range(3)] if i % 2 == 0 else None for i in range(n_rows)], dtype='object') +list_mixed_types_col = pd.Series([ + [ + {'int': i, 'string': None, 'bool': None}, + {'int': None, 'string': "string_" + str(i), 'bool': None}, + {'int': None, 'string': None, 'bool': bool(i % 2)}, + {'int': None, 'string': None, 'bool': None} + ] for i in range(n_rows) +], dtype='object') +list_nested_col = pd.Series([generate_list_nested() for _ in range(n_rows)], dtype='object') + +# Creating the DataFrame with only the new column +df_nested_list = pd.DataFrame({ + 'list': list_col, + 'list_nullable': list_nullable_col, + 'list_mixed_types': list_mixed_types_col, + 'list_nested': list_nested_col +}) + +# Types +list_type = pa.list_(pa.int32()) +list_mixed_type = pa.list_( + pa.struct([ + pa.field('int', pa.int32()), + pa.field('string', pa.string()), + pa.field('bool', pa.bool_()) + ]) +) +list_nested_type = pa.list_(pa.list_(pa.list_(pa.int32()))) + +# Define the schema +schema = pa.schema([ + ('list', list_type), + ('list_nullable', list_type), + ('list_mixed_types', list_mixed_type), + ('list_nested', list_nested_type), +]) + +parquet_file = 'output/lists.parquet' +# Create a PyArrow Table +table = pa.Table.from_pandas(df_nested_list, schema=schema) + +# Check if the file exists and remove it +if os.path.exists(parquet_file): + os.remove(parquet_file) + +# Write the PyArrow Table to a Parquet file +with pq.ParquetWriter(parquet_file, schema, compression='GZIP') as writer: + writer.write_table(table) + +pd.set_option('display.max_columns', None) # Show all columns +pd.set_option('display.max_rows', None) # Show all rows +pd.set_option('display.width', None) # Auto-detect the width for displaying +pd.set_option('display.max_colwidth', None) # Show complete text in each cell + +# Show the first few rows of the DataFrame for verification +print(df_nested_list.head(10)) diff --git a/src/lib/parquet/resources/python/generators/maps.py b/src/lib/parquet/resources/python/generators/maps.py new file mode 100644 index 000000000..8bee49c26 --- /dev/null +++ b/src/lib/parquet/resources/python/generators/maps.py @@ -0,0 +1,193 @@ +import pandas as pd +import random +import os +import pyarrow as pa +import pyarrow.parquet as pq +import sys + +pd.set_option('display.max_columns', None) # Show all columns +pd.set_option('display.max_rows', None) # Show all rows +pd.set_option('display.width', None) # Auto-detect the width for displaying +pd.set_option('display.max_colwidth', None) # Show complete text in each cell + +# Number of rows to generate +n_rows = 100 + +# Functions to generate the data +def generate_map_of_maps(): + return { + f'outer_key_{i}': { + f'inner_key_{j}': random.randint(1, 10) + for j in range(random.randint(1, 3)) + } + for i in range(random.randint(1, 3)) + } + +def generate_map_complex_nested_list(): + return [ + [ + { + 'int': random.randint(1, 10), + 'string': f'string_{i}_{j}' + } + for j in range(random.randint(1, 3)) + ] + for i in range(random.randint(1, 3)) + ] + +def generate_map_of_lists(): + return {f'key_{i}': [random.randint(1, 10) for _ in range(random.randint(1, 3))] for i in range(random.randint(1, 3))} + +def generate_map_of_complex_lists(): + return { + f'key_{i}': [ + { + 'int': random.randint(1, 10), + 'string': f'string_{i}_{j}', + 'bool': bool(random.getrandbits(1)) + } + for j in range(random.randint(1, 3)) + ] + for i in range(random.randint(1, 3)) + } + +def generate_map_of_list_of_map_of_lists(): + return { + f'key_{i}': [ + { + f'string_{i}_{j}_{k}': [random.randint(1, 10) for _ in range(random.randint(1, 3))] + for k in range(random.randint(1, 3)) + } + for j in range(random.randint(1, 3)) + ] + for i in range(random.randint(1, 3)) + } + +def generate_map_of_structs(): + map_of_structs_data = [] + for i in range(n_rows): + # Generating a map where each value is a struct with an Int32 and a String field + map_of_structs_value = { + f'key_{j}': { + 'int_field': j, + 'string_field': f'string_{j}' + } for j in range(3) + } + map_of_structs_data.append(map_of_structs_value) + return map_of_structs_data + +def generate_map_of_struct_of_structs(n_rows): + map_of_struct_of_structs_data = [] # List to hold all the data + for i in range(n_rows): + map_of_struct_of_structs_value = { + f'key_{j}': { + 'struct': { + 'nested_struct': { + 'int': random.randint(1, 100), + 'string': f'string_{j}' + } + } + } for j in range(3) # Creating 3 key-value pairs in each map + } + map_of_struct_of_structs_data.append(map_of_struct_of_structs_value) + return map_of_struct_of_structs_data + +# Columns +map_col = [{"key_" + str(i): i} for i in range(n_rows)] +map_nullable_col = pd.Series([{"key_" + str(i): i} if i % 2 == 0 else None for i in range(n_rows)], dtype='object') +map_of_maps_col = pd.Series([generate_map_of_maps() for _ in range(n_rows)], dtype='object') +map_of_lists_col = pd.Series([generate_map_of_lists() for _ in range(n_rows)], dtype='object') +map_of_complex_lists_col = pd.Series([generate_map_of_complex_lists() for _ in range(n_rows)], dtype='object') +map_of_list_of_map_of_lists_col = pd.Series([generate_map_of_list_of_map_of_lists() for _ in range(n_rows)], dtype='object') +map_of_structs_col = generate_map_of_structs() +map_of_struct_of_structs_col = generate_map_of_struct_of_structs(n_rows) + +# Creating the DataFrame with only the new column +df_nested_list = pd.DataFrame({ + 'map': map_col, + 'map_nullable': map_nullable_col, + 'map_of_maps': map_of_maps_col, + 'map_of_lists': map_of_lists_col, + 'map_of_complex_lists': map_of_complex_lists_col, + 'map_of_list_of_map_of_lists': map_of_list_of_map_of_lists_col, + 'map_of_structs': map_of_structs_col, + 'map_of_struct_of_structs': map_of_struct_of_structs_col +}) + +# Types +map_type = pa.map_(pa.string(), pa.int32()) +map_of_maps_type = pa.map_( + pa.string(), + pa.map_( + pa.string(), + pa.int32() + ) +) +map_of_lists_type = pa.map_(pa.string(), pa.list_(pa.int32())) +map_of_complex_lists_element_type = pa.struct([ + pa.field('int', pa.int32()), + pa.field('string', pa.string()), + pa.field('bool', pa.bool_()) +]) +map_of_complex_lists_type = pa.map_(pa.string(), pa.list_(map_of_complex_lists_element_type)) + +map_of_list_of_map_of_lists_inner_list_map_type = pa.map_(pa.string(), pa.list_(pa.int32())) +map_of_list_of_map_of_lists_inner_list_type = pa.list_(map_of_list_of_map_of_lists_inner_list_map_type) +map_of_list_of_map_of_lists_type = pa.map_(pa.string(), map_of_list_of_map_of_lists_inner_list_type) + +map_of_structs_struct = pa.struct([ + pa.field('int_field', pa.int32()), + pa.field('string_field', pa.string()) +]) + +# Schema for the map of structs +map_of_structs_type = pa.map_(pa.string(), map_of_structs_struct) + +# Schema for the map of struct of structs +map_of_struct_of_structs_struct_struct_struct_type = pa.struct([ + pa.field('int', pa.int32()), + pa.field('string', pa.string()) +]) + +# Define the schema for the intermediate struct `struct` +map_of_struct_of_structs_struct_struct_type = pa.struct([ + pa.field('nested_struct', map_of_struct_of_structs_struct_struct_struct_type) +]) + +# Define the schema for the outer struct which includes the 'struct' key +map_of_struct_of_structs_struct_type = pa.struct([ + pa.field('struct', map_of_struct_of_structs_struct_struct_type) +]) + +# Define the schema for the map `map_of_struct_of_structs` +map_of_struct_of_structs_type = pa.map_( + pa.field('key', pa.string(), nullable=False), # Map keys must be non-nullable + pa.field('value', map_of_struct_of_structs_struct_type) +) + +# Define the schema +schema = pa.schema([ + ('map', map_type), + ('map_nullable', map_type), + ('map_of_maps', map_of_maps_type), + ('map_of_lists', map_of_lists_type), + ('map_of_complex_lists', map_of_complex_lists_type), + ('map_of_list_of_map_of_lists', map_of_list_of_map_of_lists_type), + ('map_of_structs', map_of_structs_type), + ('map_of_struct_of_structs', map_of_struct_of_structs_type), +]) + +parquet_file = 'output/maps.parquet' +# Create a PyArrow Table +table = pa.Table.from_pandas(df_nested_list, schema=schema) + +# Check if the file exists and remove it +if os.path.exists(parquet_file): + os.remove(parquet_file) + +# Write the PyArrow Table to a Parquet file +with pq.ParquetWriter(parquet_file, schema, compression='GZIP') as writer: + writer.write_table(table) + +# Show the first few rows of the DataFrame for verification +print(df_nested_list.head(1)) diff --git a/src/lib/parquet/resources/python/generators/orders.py b/src/lib/parquet/resources/python/generators/orders.py new file mode 100644 index 000000000..e01d21bf7 --- /dev/null +++ b/src/lib/parquet/resources/python/generators/orders.py @@ -0,0 +1,84 @@ +import pandas as pd +import pyarrow as pa +import pyarrow.parquet as pq +from faker import Faker +import uuid +from datetime import datetime +import random + +# Initialize Faker +fake = Faker() + +# Number of rows you want in your Parquet file +num_rows = 100000 + +# Generate data +order_ids = [str(uuid.uuid4()) for _ in range(num_rows)] +total_prices = [round(random.uniform(50.0, 200.0), 2) for _ in range(num_rows)] +discounts = [round(random.uniform(0.0, 50.0), 2) for _ in range(num_rows)] +created_at = [datetime.now() for _ in range(num_rows)] +updated_at = [datetime.now() for _ in range(num_rows)] + +customers = [{'customer_id': str(uuid.uuid4()), 'first_name': fake.first_name(), 'last_name': fake.last_name(), 'email': fake.email()} for _ in range(num_rows)] + +addresses = [{'address_id': str(uuid.uuid4()), 'street': fake.street_address(), 'city': fake.city(), 'state': fake.state(), 'zip': fake.zipcode(), 'country': fake.country()} for _ in range(num_rows)] + +order_lines = [[{'order_line_id': str(uuid.uuid4()), 'product_id': str(uuid.uuid4()), 'quantity': random.randint(1, 10), 'price': round(random.uniform(1.0, 50.0), 2)} for _ in range(random.randint(1, 5))] for _ in range(num_rows)] + +notes = [[{'note_id': str(uuid.uuid4()), 'note_text': fake.text()} for _ in range(random.randint(1, 3))] for _ in range(num_rows)] + +# Create a DataFrame +df = pd.DataFrame({ + 'order_id': order_ids, + 'total_price': total_prices, + 'discount': discounts, + 'created_at': created_at, + 'updated_at': updated_at, + 'customer': customers, + 'address': addresses, + 'order_lines': order_lines, + 'notes': notes +}) + +# Define schema +schema = pa.schema([ + ('order_id', pa.string()), + ('total_price', pa.float32()), + ('discount', pa.float32()), + ('created_at', pa.timestamp('ns')), + ('updated_at', pa.timestamp('ns')), + ('customer', pa.struct([ + ('customer_id', pa.string()), + ('first_name', pa.string()), + ('last_name', pa.string()), + ('email', pa.string()) + ])), + ('address', pa.struct([ + ('address_id', pa.string()), + ('street', pa.string()), + ('city', pa.string()), + ('state', pa.string()), + ('zip', pa.string()), + ('country', pa.string()) + ])), + ('order_lines', pa.list_( + pa.struct([ + ('order_line_id', pa.string()), + ('product_id', pa.string()), + ('quantity', pa.int32()), + ('price', pa.float32()) + ]) + )), + ('notes', pa.list_( + pa.struct([ + ('note_id', pa.string()), + ('note_text', pa.string()) + ]) + )) +]) + +# Convert DataFrame to PyArrow Table +table = pa.table(df, schema=schema) + +# Write out as Parquet file with Snappy compression +pq.write_table(table, 'output/orders.parquet', compression='gzip') diff --git a/src/lib/parquet/resources/python/generators/primitives.py b/src/lib/parquet/resources/python/generators/primitives.py new file mode 100644 index 000000000..4c94f9b0c --- /dev/null +++ b/src/lib/parquet/resources/python/generators/primitives.py @@ -0,0 +1,110 @@ +# Importing necessary libraries +import pandas as pd +import random +import os +import json +from datetime import datetime, timedelta, time +import uuid +from enum import Enum +import pyarrow as pa +import pyarrow.parquet as pq + +# Number of rows to generate +n_rows = 100 + +class Color(Enum): + RED = 1 + GREEN = 2 + BLUE = 3 + +int32_col = pd.Series(range(n_rows), dtype='int32') +int64_col = pd.Series(range(n_rows), dtype='int64') +bool_col = pd.Series([random.choice([True, False]) for _ in range(n_rows)], dtype='bool') +string_col = pd.Series(['string_' + str(i) for i in range(n_rows)], dtype='string') +json_col = pd.Series([json.dumps({'key': random.randint(1, 10)}) for _ in range(n_rows)], dtype='string') +date_col = pd.Series([datetime.now().date() + timedelta(days=i) for i in range(n_rows)], dtype='object') +timestamp_col = pd.Series([pd.Timestamp(datetime.now() + timedelta(seconds=i * 10)) for i in range(n_rows)], dtype='datetime64[ns]') +time_col = pd.Series([time(hour=i % 24, minute=(i * 2) % 60, second=(i * 3) % 60) for i in range(n_rows)], dtype='object') +uuid_col = pd.Series([str(uuid.uuid4()) for _ in range(n_rows)], dtype='string') +enum_col = pd.Series([random.choice(list(Color)).name for _ in range(n_rows)], dtype='string') + +int32_nullable_col = pd.Series([i if i % 2 == 0 else None for i in range(n_rows)], dtype='Int32') +int64_nullable_col = pd.Series([i if i % 2 == 0 else None for i in range(n_rows)], dtype='Int64') +bool_nullable_col = pd.Series([True if i % 2 == 0 else None for i in range(n_rows)], dtype='boolean') +string_nullable_col = pd.Series(['string_' + str(i) if i % 2 == 0 else None for i in range(n_rows)], dtype='string') +json_nullable_col = pd.Series([json.dumps({'key': random.randint(1, 10)}) if i % 2 == 0 else None for i in range(n_rows)], dtype='string') +date_nullable_col = pd.Series([datetime.now().date() + timedelta(days=i) if i % 2 == 0 else None for i in range(n_rows)], dtype='object') +timestamp_nullable_col = pd.Series([pd.Timestamp(datetime.now() + timedelta(seconds=i * 10)) if i % 2 == 0 else None for i in range(n_rows)], dtype='object') +time_nullable_col = pd.Series([time(hour=i % 24, minute=(i * 2) % 60, second=(i * 3) % 60) if i % 2 == 0 else None for i in range(n_rows)], dtype='object') +uuid_nullable_col = pd.Series([str(uuid.uuid4()) if i % 2 == 0 else None for i in range(n_rows)], dtype='string') +enum_nullable_col = pd.Series([random.choice(list(Color)).name if i % 2 == 0 else None for i in range(n_rows)], dtype='string') + +# Creating the DataFrame with only the new column +df_nested_list = pd.DataFrame({ + 'int32': int32_col, + 'int32_nullable': int32_nullable_col, + 'int64': int64_col, + 'int64_nullable': int64_nullable_col, + 'bool': bool_col, + 'bool_nullable': bool_nullable_col, + 'string': string_col, + 'string_nullable': string_nullable_col, + 'json': json_col, + 'json_nullable': json_nullable_col, + 'date': date_col, + 'date_nullable': date_nullable_col, + 'timestamp': timestamp_col, + 'timestamp_nullable': timestamp_nullable_col, + 'time': time_col, + 'time_nullable': time_nullable_col, + 'uuid': uuid_col, + 'uuid_nullable': uuid_nullable_col, + 'enum': enum_col, + 'enum_nullable': enum_nullable_col, +}) + +# Define the schema +schema = pa.schema([ + ('int32', pa.int32()), + ('int32_nullable', pa.int32()), + ('int64', pa.int64()), + ('int64_nullable', pa.int64()), + ('bool', pa.bool_()), + ('bool_nullable', pa.bool_()), + ('string', pa.string()), + ('string_nullable', pa.string()), + ('json', pa.string()), + ('json_nullable', pa.string()), + ('date', pa.date32()), + ('date_nullable', pa.date32()), + ('timestamp', pa.timestamp('ns')), + ('timestamp_nullable', pa.timestamp('ns')), + ('time', pa.time64('ns')), + ('time_nullable', pa.time64('ns')), + ('uuid', pa.string()), + ('uuid_nullable', pa.string()), + ('enum', pa.string()), + ('enum_nullable', pa.string()), +]) + +# Create a PyArrow Table +table = pa.Table.from_pandas(df_nested_list, schema=schema) + +# Define the Parquet file path +parquet_file = 'output/primitives.parquet' + +# Check if the file exists and remove it +if os.path.exists(parquet_file): + os.remove(parquet_file) + +# Write the PyArrow Table to a Parquet file +with pq.ParquetWriter(parquet_file, schema, compression='GZIP') as writer: + writer.write_table(table) + +pd.set_option('display.max_columns', None) # Show all columns +pd.set_option('display.max_rows', None) # Show all rows +pd.set_option('display.width', None) # Auto-detect the width for displaying +pd.set_option('display.max_colwidth', None) # Show complete text in each cell + +# Show the first few rows of the DataFrame for verification +print(df_nested_list.head(10)) diff --git a/src/lib/parquet/resources/python/generators/structs.py b/src/lib/parquet/resources/python/generators/structs.py new file mode 100644 index 000000000..e568e8f53 --- /dev/null +++ b/src/lib/parquet/resources/python/generators/structs.py @@ -0,0 +1,393 @@ +import pandas as pd +import random +import os +import pyarrow as pa +import json +import pyarrow.parquet as pq +import sys + +# Number of rows to generate +n_rows = 100 + +# Functions to generate the data +def generate_struct_flat(): + struct_flat_data = [] + for i in range(n_rows): + string_value = f'string_{i}' + string_nullable_value = f'string_{i}' if i % 2 == 0 else None + int_value = i + int_nullable_value = i if i % 2 == 0 else None + bool_value = i % 2 == 0 + bool_nullable_value = i % 2 == 0 if i % 2 == 0 else None + list_of_ints_value = [random.randint(1, 10) for _ in range(3)] + list_of_strings_value = [f'str_{j}' for j in range(3)] + map_of_string_int_value = {f'key_{j}': j for j in range(3)} + map_of_int_int_value = {j: j for j in range(3)} + + struct_flat_element = { + 'string': string_value, + 'string_nullable': string_nullable_value, + 'int': int_value, + 'int_nullable': int_nullable_value, + 'bool': bool_value, + 'bool_nullable': bool_nullable_value, + 'list_of_ints': list_of_ints_value, + 'list_of_strings': list_of_strings_value, + 'map_of_string_int': map_of_string_int_value, + 'map_of_int_int': map_of_int_int_value + } + + struct_flat_data.append(struct_flat_element) + + return struct_flat_data + +def generate_struct_nested(): + struct_nested_data = [] + for i in range(n_rows): + string_value = f'string_{i}' + int_value = i + list_of_ints_value = [random.randint(1, 10) for _ in range(3)] + map_of_string_int_value = {f'key_{j}': j for j in range(3)} + + struct_element = { + 'int': int_value, + 'list_of_ints': list_of_ints_value, + 'map_of_string_int': map_of_string_int_value + } + + struct_nested_element = { + 'string': string_value, + 'struct_flat': struct_element + } + + struct_nested_data.append(struct_nested_element) + + return struct_nested_data + +def generate_struct_nested_with_list_of_lists(): + struct_nested_data = [] + for i in range(n_rows): + string_value = f'string_{i}' + int_value = i + # Generating list of lists of integers + list_of_list_of_ints_value = [[random.randint(1, 10) for _ in range(random.randint(1, 3))] for _ in range(random.randint(1, 3))] + + struct_element = { + 'int': int_value, + 'list_of_list_of_ints': list_of_list_of_ints_value + } + + struct_nested_element = { + 'string': string_value, + 'struct': struct_element + } + + struct_nested_data.append(struct_nested_element) + + return struct_nested_data + +def generate_struct_nested_with_list_of_maps(): + struct_nested_data = [] + for i in range(n_rows): + string_value = f'string_{i}' + int_value = i + list_of_map_of_string_int_value = [{f'key_{k}': random.randint(1, 10) for k in range(3)} for _ in range(3)] + + struct_element = { + 'int': int_value, + 'list_of_map_of_string_int': list_of_map_of_string_int_value + } + + struct_nested_element = { + 'string': string_value, + 'struct': struct_element + } + + struct_nested_data.append(struct_nested_element) + + return struct_nested_data + +def generate_struct_nested_with_map_of_list_of_ints(): + struct_nested_data = [] + for i in range(n_rows): + string_value = f'string_{i}' + int_value = i + map_of_int_list_of_string_value = {j: [f'str_{k}' for k in range(3)] for j in range(3)} + + struct_element = { + 'int': int_value, + 'map_of_int_list_of_string': map_of_int_list_of_string_value + } + + struct_nested_element = { + 'string': string_value, + 'struct': struct_element + } + + struct_nested_data.append(struct_nested_element) + + return struct_nested_data + +def generate_struct_nested_with_map_of_string_map_of_string_string(): + struct_nested_data = [] + for i in range(n_rows): + string_value = f'string_{i}' + int_value = i + + map_of_string_map_of_string_string_value = { + f'outer_key_{j}': {f'inner_key_{k}': f'inner_value_{k}' for k in range(3)} + for j in range(3) + } + + struct_element = { + 'int': int_value, + 'map_of_string_map_of_string_string': map_of_string_map_of_string_string_value + } + + struct_nested_element = { + 'string': string_value, + 'struct': struct_element + } + + struct_nested_data.append(struct_nested_element) + + return struct_nested_data + +def generate_struct_with_list_and_map_of_structs(): + struct_data = [] + for i in range(n_rows): + string_value = f'string_{i}' + + list_of_structs_value = [{ + 'int': j, + 'list': [random.randint(1, 10) for _ in range(3)] + } for j in range(3)] + + map_of_string_structs_value = { + f'key_{j}': { + 'int': j, + 'list': [random.randint(1, 10) for _ in range(3)] + } for j in range(3) + } + + struct_nested = { + 'int': i, + 'list_of_structs': list_of_structs_value, + 'map_of_string_structs': map_of_string_structs_value + } + + struct_element = { + 'string': string_value, + 'struct': struct_nested + } + + struct_data.append(struct_element) + + return struct_data + +def generate_struct_deeply_nested(): + struct_deeply_nested_data = [] + for i in range(n_rows): + json_value = json.dumps({"key": "value"}) + struct_4 = { + 'string': f'string_{i}', + 'json': json_value + } + struct_3 = { + 'float': random.uniform(0.0, 1.0), + 'struct_4': struct_4 + } + struct_2 = { + 'bool': bool(i % 2), + 'struct_3': struct_3 + } + struct_1 = { + 'string': f'string_{i}', + 'struct_2': struct_2 + } + struct_0 = { + 'int': i, + 'struct_1': struct_1 + } + struct_deeply_nested = { + 'struct_0': struct_0 + } + struct_deeply_nested_data.append(struct_deeply_nested) + return struct_deeply_nested_data + +# Columns +struct_flat_col = generate_struct_flat() +struct_nested_col = generate_struct_nested() +struct_nested_with_list_of_lists_col = generate_struct_nested_with_list_of_lists() +struct_nested_with_list_of_maps_col = generate_struct_nested_with_list_of_maps() +struct_nested_with_map_of_list_of_ints_col = generate_struct_nested_with_map_of_list_of_ints() +struct_nested_with_map_of_string_map_of_string_string_col = generate_struct_nested_with_map_of_string_map_of_string_string() +struct_with_list_and_map_of_structs_col = generate_struct_with_list_and_map_of_structs() +struct_deeply_nested_col = generate_struct_deeply_nested() + +# Creating the DataFrame with only the new column +df_nested_list = pd.DataFrame({ + 'struct_flat': struct_flat_col, + 'struct_nested': struct_nested_col, + 'struct_nested_with_list_of_lists': struct_nested_with_list_of_lists_col, + 'struct_nested_with_list_of_maps': struct_nested_with_list_of_maps_col, + 'struct_nested_with_map_of_list_of_ints': struct_nested_with_map_of_list_of_ints_col, + 'struct_nested_with_map_of_string_map_of_string_string': struct_nested_with_map_of_string_map_of_string_string_col, + 'struct_with_list_and_map_of_structs': struct_with_list_and_map_of_structs_col, + 'struct_deeply_nested': struct_deeply_nested_col +}) + +# Types +list_of_ints_type = pa.list_(pa.int32()) +list_of_strings_type = pa.list_(pa.string()) +map_of_string_int_type = pa.map_(pa.string(), pa.int32()) +map_of_int_int_type = pa.map_(pa.int32(), pa.int32()) +list_of_list_of_ints_type = pa.list_(list_of_ints_type) +list_of_map_of_string_int_type = pa.list_(pa.map_(pa.string(), pa.int32())) +map_of_int_list_of_string = pa.map_(pa.int32(), pa.list_(pa.string())) +map_of_string_string_type = pa.map_(pa.string(), pa.string()) +map_string_map_of_string_string_type = pa.map_(pa.string(), map_of_string_string_type) +struct_with_int_and_list_of_ints_type = pa.struct([ + pa.field('int', pa.int32()), + pa.field('list', pa.list_(pa.int32())) +]) + +#### struct_flat +struct_flat_type = pa.struct([ + pa.field('string', pa.string()), + pa.field('string_nullable', pa.string()), + pa.field('int', pa.int32()), + pa.field('int_nullable', pa.int32()), + pa.field('bool', pa.bool_()), + pa.field('bool_nullable', pa.bool_()), + pa.field('list_of_ints', list_of_ints_type), + pa.field('list_of_strings', list_of_strings_type), + pa.field('map_of_string_int', map_of_string_int_type), + pa.field('map_of_int_int', map_of_int_int_type), +]) + +#### Struct Nested +list_of_ints_type = pa.list_(pa.int32()) +map_of_string_int_type = pa.map_(pa.string(), pa.int32()) + +struct_nested_struct_flat_type = pa.struct([ + pa.field('int', pa.int32()), + pa.field('list_of_ints', list_of_ints_type), + pa.field('map_of_string_int', map_of_string_int_type) +]) + +struct_nested_type = pa.struct([ + pa.field('string', pa.string()), + pa.field('struct_flat', struct_nested_struct_flat_type) +]) + +#### Struct with a list of lists of integers +struct_nested_with_list_of_lists_struct_type = pa.struct([ + pa.field('int', pa.int32()), + pa.field('list_of_list_of_ints', list_of_list_of_ints_type) +]) + +struct_nested_with_list_of_lists_type = pa.struct([ + pa.field('string', pa.string()), + pa.field('struct', struct_nested_with_list_of_lists_struct_type) +]) + +#### Struct with list of maps of string to int +struct_type = pa.struct([ + pa.field('int', pa.int32()), + pa.field('list_of_map_of_string_int', list_of_map_of_string_int_type) +]) + +struct_nested_with_list_of_maps_type = pa.struct([ + pa.field('string', pa.string()), + pa.field('struct', struct_type) +]) +#### Struct with map of int to list of string +struct_nested_with_map_of_list_of_ints_struct_type = pa.struct([ + pa.field('int', pa.int32()), + pa.field('map_of_int_list_of_string', map_of_int_list_of_string) +]) +struct_nested_with_map_of_list_of_ints_type = pa.struct([ + pa.field('string', pa.string()), + pa.field('struct', struct_nested_with_map_of_list_of_ints_struct_type) +]) +#### Struct with map of string to map of string to string +struct_nested_with_map_of_string_map_of_string_string_struct_type = pa.struct([ + pa.field('int', pa.int32()), + pa.field('map_of_string_map_of_string_string', map_string_map_of_string_string_type) +]) +struct_nested_with_map_of_string_map_of_string_string_type = pa.struct([ + pa.field('string', pa.string()), + pa.field('struct', struct_nested_with_map_of_string_map_of_string_string_struct_type) +]) +#### Struct with list and map of structs +struct_with_list_and_map_of_structs_list_of_structs_type = pa.list_(struct_with_int_and_list_of_ints_type) +struct_with_list_and_map_of_structs_map_of_string_structs_type = pa.map_(pa.string(), struct_with_int_and_list_of_ints_type) + +struct_with_list_and_map_of_structs_struct_type = pa.struct([ + pa.field('int', pa.int32()), + pa.field('list_of_structs', struct_with_list_and_map_of_structs_list_of_structs_type), + pa.field('map_of_string_structs', struct_with_list_and_map_of_structs_map_of_string_structs_type) +]) + +struct_with_list_and_map_of_structs_type = pa.struct([ + pa.field('string', pa.string()), + pa.field('struct', struct_with_list_and_map_of_structs_struct_type) +]) +#### Struct deeply nested +struct_4_type = pa.struct([ + pa.field('string', pa.string()), + pa.field('json', pa.string()) +]) +struct_3_type = pa.struct([ + pa.field('float', pa.float32()), + pa.field('struct_4', struct_4_type) +]) +struct_2_type = pa.struct([ + pa.field('bool', pa.bool_()), + pa.field('struct_3', struct_3_type) +]) +struct_1_type = pa.struct([ + pa.field('string', pa.string()), + pa.field('struct_2', struct_2_type) +]) +struct_0_type = pa.struct([ + pa.field('int', pa.int32()), + pa.field('struct_1', struct_1_type) +]) +struct_deeply_nested_type = pa.struct([ + pa.field('struct_0', struct_0_type) +]) + +# Define the schema +schema = pa.schema([ + ('struct_flat', struct_flat_type), + ('struct_nested', struct_nested_type), + ('struct_nested_with_list_of_lists', struct_nested_with_list_of_lists_type), + ('struct_nested_with_list_of_maps', struct_nested_with_list_of_maps_type), + ('struct_nested_with_map_of_list_of_ints', struct_nested_with_map_of_list_of_ints_type), + ('struct_nested_with_map_of_string_map_of_string_string', struct_nested_with_map_of_string_map_of_string_string_type), + ('struct_with_list_and_map_of_structs', struct_with_list_and_map_of_structs_type), + ('struct_deeply_nested', struct_deeply_nested_type), +]) + +parquet_file = 'output/structs.parquet' + +# Create a PyArrow Table +table = pa.Table.from_pandas(df_nested_list, schema=schema) + +# Check if the file exists and remove it +if os.path.exists(parquet_file): + os.remove(parquet_file) + +# Write the PyArrow Table to a Parquet file +with pq.ParquetWriter(parquet_file, schema, compression='GZIP') as writer: + writer.write_table(table) + +pd.set_option('display.max_columns', None) # Show all columns +pd.set_option('display.max_rows', None) # Show all rows +pd.set_option('display.width', None) # Auto-detect the width for displaying +pd.set_option('display.max_colwidth', None) # Show complete text in each cell + +# Show the first few rows of the DataFrame for verification +print(df_nested_list.head(10)) diff --git a/src/lib/parquet/resources/python/output/.gitkeep b/src/lib/parquet/resources/python/output/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/src/lib/parquet/resources/python/requirements.txt b/src/lib/parquet/resources/python/requirements.txt new file mode 100644 index 000000000..f46513006 --- /dev/null +++ b/src/lib/parquet/resources/python/requirements.txt @@ -0,0 +1,3 @@ +pandas +pyarrow +faker \ No newline at end of file diff --git a/src/lib/parquet/src/Flow/Parquet/BinaryReader.php b/src/lib/parquet/src/Flow/Parquet/BinaryReader.php new file mode 100644 index 000000000..025cc60a7 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/BinaryReader.php @@ -0,0 +1,99 @@ + + */ + public function readBits(int $total) : array; + + public function readBoolean() : bool; + + /** + * @return array + */ + public function readBooleans(int $total) : array; + + public function readByte() : int; + + /** + * @return array> + */ + public function readByteArrays(int $total) : array; + + public function readBytes(int $total) : Bytes; + + public function readDouble() : float; + + /** + * @return array + */ + public function readDoubles(int $total) : array; + + public function readFloat() : float; + + /** + * @return array + */ + public function readFloats(int $total) : array; + + public function readInt32() : int; + + public function readInt64() : int; + + /** + * @return array + */ + public function readInt96() : array; + + /** + * @return array + */ + public function readInts32(int $total) : array; + + /** + * @return array + */ + public function readInts64(int $total) : array; + + /** + * @return array> + */ + public function readInts96(int $total) : array; + + public function readString() : string; + + public function readStrings(int $total) : array; + + public function readUInt32() : int; + + public function readUInt64() : int; + + /** + * @return array + */ + public function readUInts32(int $total) : array; + + /** + * @return array + */ + public function readUInts64(int $total) : array; + + public function readVarInt() : int; + + public function remainingLength() : DataSize; + + public function seekBits(int $bits) : void; + + public function seekBytes(int $bytes) : void; +} diff --git a/src/lib/parquet/src/Flow/Parquet/BinaryReader/BinaryBufferReader.php b/src/lib/parquet/src/Flow/Parquet/BinaryReader/BinaryBufferReader.php new file mode 100644 index 000000000..0317c0a5a --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/BinaryReader/BinaryBufferReader.php @@ -0,0 +1,417 @@ +position = new DataSize(0); + $this->remainingLength = new DataSize(\strlen($buffer) * 8); + $this->length = new DataSize(\strlen($buffer) * 8); + } + + public function length() : DataSize + { + return $this->length; + } + + public function position() : DataSize + { + return $this->position; + } + + public function readBit() : int + { + $bytePosition = $this->position->bytes(); + $bitOffset = $this->position->bits(); + + $byte = \ord($this->buffer[$bytePosition]); + $bit = ($byte >> $bitOffset) & 1; + + $this->position->add(1); + $this->remainingLength->sub(1); + + return $bit; + } + + /** + * @return array + */ + public function readBits(int $total) : array + { + $bits = []; + $bytePosition = $this->position()->bytes(); + $bitOffset = $this->position->bits() % 8; + $bytesNeeded = \intdiv($bitOffset + $total - 1, 8) + 1; + $currentBytes = \substr($this->buffer, $bytePosition, $bytesNeeded); + + for ($i = 0; $i < $bytesNeeded; $i++) { + $byte = \ord($currentBytes[$i]); + + for ($j = $bitOffset; $j < 8; $j++) { + $bits[] = ($byte >> $j) & 1; + + if (--$total === 0) { + $this->position->add($i * 8 + $j + 1 - $bitOffset); + $this->remainingLength->sub($i * 8 + $j + 1 - $bitOffset); + + return $bits; + } + } + $bitOffset = 0; + } + + return $bits; // This should never be reached + } + + public function readBoolean() : bool + { + return (bool) $this->readBit(); + } + + public function readBooleans(int $total) : array + { + $bits = $this->readBits($total); + $booleans = []; + + foreach ($bits as $bit) { + $booleans[] = (bool) $bit; + } + + return $booleans; + } + + public function readByte() : int + { + $byte = \ord($this->buffer[$this->position()->bytes()]); + $this->position->add(8); + $this->remainingLength->sub(8); + + return $byte; + } + + public function readByteArrays(int $total) : array + { + $position = $this->position()->bytes(); + $byteArrays = []; + + while (\count($byteArrays) < $total) { + $rawStr = \substr($this->buffer, $position, 4); + + if ($rawStr === '') { + break; + } + // Read the length of the string from the first byte + $bytesLength = \unpack($this->byteOrder === ByteOrder::LITTLE_ENDIAN ? 'V' : 'N', $rawStr)[1]; + $position += 4; + + $byteStr = \substr($this->buffer, $position, $bytesLength); + $byteArray = []; + + for ($i = 0; $i < $bytesLength; $i++) { + $byteArray[] = \ord($byteStr[$i]); + } + + $byteArrays[] = $byteArray; + $position += $bytesLength; + } + + $this->position->add($position * 8); + $this->remainingLength->sub($position * 8); + + return $byteArrays; + } + + public function readBytes(int $total) : Bytes + { + $bytes = \array_values(\unpack('C*', \substr($this->buffer, $this->position()->bytes(), $total))); + + $this->position->add(8 * $total); + $this->remainingLength->sub(8 * $total); + + return new Bytes($bytes); + } + + public function readDouble() : float + { + $result = \unpack( + $this->byteOrder === ByteOrder::LITTLE_ENDIAN ? 'e' : 'E', + \substr($this->buffer, $this->position()->bytes(), 8) + )[1]; + + $this->position->add(64); + $this->remainingLength->sub(64); + + return $result; + } + + public function readDoubles(int $total) : array + { + $doubleBytes = \array_chunk($this->readBytes(8 * $total)->toArray(), 8); + + $doubles = []; + + foreach ($doubleBytes as $bytes) { + $doubles[] = \unpack($this->byteOrder === ByteOrder::LITTLE_ENDIAN ? 'e' : 'E', \pack('C*', ...$bytes))[1]; + } + + return $doubles; + } + + public function readFloat() : float + { + $result = \unpack( + $this->byteOrder === ByteOrder::LITTLE_ENDIAN ? 'g' : 'G', + \substr($this->buffer, $this->position()->bytes(), 4) + )[1]; + + $this->position->add(32); + $this->remainingLength->sub(32); + + return $result; + } + + public function readFloats(int $total) : array + { + $floatBytes = \array_chunk($this->readBytes(4 * $total)->toArray(), 4); + + $floats = []; + + foreach ($floatBytes as $bytes) { + $floats[] = \unpack($this->byteOrder === ByteOrder::LITTLE_ENDIAN ? 'g' : 'G', \pack('C*', ...$bytes))[1]; + } + + return $floats; + } + + public function readInt32() : int + { + $bytes = $this->readBytes(4)->toArray(); + + if ($this->byteOrder === ByteOrder::LITTLE_ENDIAN) { + return $bytes[0] | ($bytes[1] << 8) | ($bytes[2] << 16) | ($bytes[3] << 24); + } + + return ($bytes[0] << 24) | ($bytes[1] << 16) | ($bytes[2] << 8) | $bytes[3]; + } + + public function readInt64() : int + { + $bytes = $this->readBytes(8)->toArray(); + + if ($this->byteOrder === ByteOrder::LITTLE_ENDIAN) { + return $bytes[0] | ($bytes[1] << 8) | ($bytes[2] << 16) | ($bytes[3] << 24) | + ($bytes[4] << 32) | ($bytes[5] << 40) | ($bytes[6] << 48) | ($bytes[7] << 56); + } + + return ($bytes[0] << 56) | ($bytes[1] << 48) | ($bytes[2] << 40) | ($bytes[3] << 32) | + ($bytes[4] << 24) | ($bytes[5] << 16) | ($bytes[6] << 8) | $bytes[7]; + } + + public function readInt96() : array + { + $position = $this->position()->bytes(); + $data = \substr($this->buffer, $position, 12); + + $int96Bytes = []; + + foreach (\str_split($data) as $byte) { + $int96Bytes[] = \ord($byte); + } + + $this->position->add(12 * 8); + $this->remainingLength->sub(12 * 8); + + return $int96Bytes; + } + + /** + * @return array + */ + public function readInts32(int $count) : array + { + $intBytes = \array_chunk($this->readBytes(4 * $count)->toArray(), 4); + $ints = []; + + foreach ($intBytes as $bytes) { + if ($this->byteOrder === ByteOrder::LITTLE_ENDIAN) { + $ints[] = $bytes[0] | ($bytes[1] << 8) | ($bytes[2] << 16) | ($bytes[3] << 24); + } else { + $ints[] = ($bytes[0] << 24) | ($bytes[1] << 16) | ($bytes[2] << 8) | $bytes[3]; + } + } + + return $ints; + } + + public function readInts64(int $count) : array + { + $intBytes = \array_chunk($this->readBytes(8 * $count)->toArray(), 8); + + $ints = []; + + foreach ($intBytes as $bytes) { + if ($this->byteOrder === ByteOrder::LITTLE_ENDIAN) { + $ints[] = $bytes[0] | ($bytes[1] << 8) | ($bytes[2] << 16) | ($bytes[3] << 24) | + ($bytes[4] << 32) | ($bytes[5] << 40) | ($bytes[6] << 48) | ($bytes[7] << 56); + } else { + $ints[] = ($bytes[0] << 56) | ($bytes[1] << 48) | ($bytes[2] << 40) | ($bytes[3] << 32) | + ($bytes[4] << 24) | ($bytes[5] << 16) | ($bytes[6] << 8) | $bytes[7]; + } + } + + return $ints; + } + + public function readInts96(int $total) : array + { + $intsData = \substr($this->buffer, $this->position()->bytes(), 12 * $total); + + $ints96 = []; + + foreach (\str_split($intsData, 12) as $data) { + $int96Bytes = []; + + foreach (\str_split($data) as $byte) { + $int96Bytes[] = \ord($byte); + } + + $ints96[] = $int96Bytes; + } + + $this->position->add(12 * $total * 8); + $this->remainingLength->sub(12 * $total * 8); + + return $ints96; + } + + public function readString() : string + { + $length = $this->readInt32(); + $string = \substr($this->buffer, $this->position()->bytes(), $length); + $this->position->add($length * 8); + $this->remainingLength->sub($length * 8); + + return $string; + } + + public function readStrings(int $total) : array + { + $position = $this->position()->bytes(); + $strings = []; + + while (\count($strings) < $total) { + $rawStr = \substr($this->buffer, $position, 4); + + if ($rawStr === '') { + break; + } + // Read the length of the string from the first byte + $strLength = \unpack($this->byteOrder === ByteOrder::LITTLE_ENDIAN ? 'V' : 'N', $rawStr)[1]; + $position += 4; + + // Read the string based on the length + $strings[] = \substr($this->buffer, $position, $strLength); + $position += $strLength; + } + + $this->position->add($position * 8); + $this->remainingLength->sub($position * 8); + + return $strings; + } + + public function readUInt32() : int + { + $bytes = $this->readBytes(4)->toArray(); + + if ($this->byteOrder === ByteOrder::LITTLE_ENDIAN) { + return $bytes[0] | ($bytes[1] << 8) | ($bytes[2] << 16) | ($bytes[3] << 24); + } + + return ($bytes[0] << 24) | ($bytes[1] << 16) | ($bytes[2] << 8) | $bytes[3]; + } + + public function readUInt64() : int + { + return $this->readInt64(); + } + + public function readUInts32(int $total) : array + { + $intBytes = \array_chunk($this->readBytes(4 * $total)->toArray(), 4); + + $ints = []; + + foreach ($intBytes as $bytes) { + if ($this->byteOrder === ByteOrder::LITTLE_ENDIAN) { + $ints[] = $bytes[0] | ($bytes[1] << 8) | ($bytes[2] << 16) | ($bytes[3] << 24); + } else { + $ints[] = ($bytes[0] << 24) | ($bytes[1] << 16) | ($bytes[2] << 8) | $bytes[3]; + } + } + + return $ints; + } + + public function readUInts64(int $total) : array + { + $intBytes = \array_chunk($this->readBytes(4 * $total)->toArray(), 4); + + $ints = []; + + foreach ($intBytes as $bytes) { + if ($this->byteOrder === ByteOrder::LITTLE_ENDIAN) { + $ints[] = $bytes[0] | ($bytes[1] << 8) | ($bytes[2] << 16) | ($bytes[3] << 24) | + ($bytes[4] << 32) | ($bytes[5] << 40) | ($bytes[6] << 48) | ($bytes[7] << 56); + } else { + $ints[] = ($bytes[0] << 56) | ($bytes[1] << 48) | ($bytes[2] << 40) | ($bytes[3] << 32) | + ($bytes[4] << 24) | ($bytes[5] << 16) | ($bytes[6] << 8) | $bytes[7]; + } + } + + return $ints; + } + + public function readVarInt() : int + { + $result = 0; + $shift = 0; + + do { + $byte = $this->readByte(); + $result |= ($byte & 0x7F) << $shift; + $shift += 7; + } while ($byte >= 0x80); + + return $result; + } + + public function remainingLength() : DataSize + { + return $this->remainingLength; + } + + public function seekBits(int $bits) : void + { + $this->position->add($bits); + $this->length->sub($bits); + } + + public function seekBytes(int $bytes) : void + { + $this->position->add($bytes * 8); + $this->remainingLength->sub($bytes * 8); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/BinaryReader/BinaryStreamReader.php b/src/lib/parquet/src/Flow/Parquet/BinaryReader/BinaryStreamReader.php new file mode 100644 index 000000000..05f102d17 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/BinaryReader/BinaryStreamReader.php @@ -0,0 +1,299 @@ +handle, 0, SEEK_END); + $this->fileLength = \ftell($this->handle); + \fseek($this->handle, 0, SEEK_SET); + + $this->bitPosition = 0; + } + + public function length() : DataSize + { + return new DataSize($this->fileLength * 8); + } + + public function position() : DataSize + { + return new DataSize($this->bitPosition); + } + + public function readBit() : int + { + if ($this->bitPosition >= $this->length()->bits()) { + throw new OutOfBoundsException('Reached the end of the file'); + } + + \fseek($this->handle, \intdiv($this->bitPosition, 8)); + $byte = \ord(\fread($this->handle, 1)); + $bit = ($byte >> ($this->bitPosition % 8)) & 1; + + $this->bitPosition++; + + return $bit; + } + + public function readBits(int $total) : array + { + if ($total < 0) { + throw new InvalidArgumentException('Count cannot be negative.'); + } + + $bits = []; + $bytePosition = \intdiv($this->bitPosition, 8); + \fseek($this->handle, $bytePosition); + + while ($total > 0) { + $byte = \ord(\fread($this->handle, 1)); + + for ($bitOffset = $this->bitPosition % 8; $bitOffset < 8; $bitOffset++) { + $bits[] = ($byte >> $bitOffset) & 1; + $total--; + $this->bitPosition++; + + if ($total === 0) { + return $bits; + } + } + } + + return $bits; + } + + public function readBoolean() : bool + { + throw new RuntimeException('Not implemented yet.'); + } + + public function readBooleans(int $total) : array + { + throw new RuntimeException('Not implemented yet.'); + } + + public function readByte() : int + { + if ($this->bitPosition % 8 !== 0) { + throw new InvalidArgumentException('Current position must be at byte boundary to read a full byte.'); + } + + \fseek($this->handle, $this->bitPosition / 8); + $byte = \ord(\fread($this->handle, 1)); + $this->bitPosition += 8; + + return $byte; + } + + public function readByteArrays(int $total) : array + { + throw new RuntimeException('Not implemented yet.'); + } + + public function readBytes(int $total) : Bytes + { + if ($total < 0) { + throw new InvalidArgumentException('Count cannot be negative.'); + } + + if ($this->bitPosition % 8 !== 0) { + throw new InvalidArgumentException('Current position must be at byte boundary to read bytes.'); + } + + \fseek($this->handle, $this->bitPosition / 8); + $bytes = \fread($this->handle, $total); + $this->bitPosition += 8 * \strlen($bytes); + + return new Bytes(\array_values(\unpack('C*', $bytes))); + } + + public function readDouble() : float + { + if ($this->bitPosition % 8 !== 0) { + throw new InvalidArgumentException('Current position must be at byte boundary to read a double.'); + } + + \fseek($this->handle, $this->bitPosition / 8); + $bytes = \fread($this->handle, 8); + $result = \unpack($this->byteOrder === ByteOrder::LITTLE_ENDIAN ? 'e' : 'E', $bytes)[1]; + $this->bitPosition += 64; + + return $result; + } + + public function readDoubles(int $total) : array + { + throw new RuntimeException('Not implemented yet.'); + } + + public function readFloat() : float + { + if ($this->bitPosition % 8 !== 0) { + throw new InvalidArgumentException('Current position must be at byte boundary to read a float.'); + } + + \fseek($this->handle, $this->bitPosition / 8); + $bytes = \fread($this->handle, 4); + $result = \unpack($this->byteOrder === ByteOrder::LITTLE_ENDIAN ? 'g' : 'G', $bytes)[1]; + $this->bitPosition += 32; + + return $result; + } + + public function readFloats(int $total) : array + { + throw new RuntimeException('Not implemented yet.'); + } + + public function readInt32() : int + { + if ($this->bitPosition % 8 !== 0) { + throw new InvalidArgumentException('Current position must be at byte boundary to read an int32.'); + } + + \fseek($this->handle, $this->bitPosition / 8); + $bytes = \array_values(\unpack('C*', \fread($this->handle, 4))); + $this->bitPosition += 32; + + return $this->byteOrder === ByteOrder::LITTLE_ENDIAN + ? $bytes[0] | ($bytes[1] << 8) | ($bytes[2] << 16) | ($bytes[3] << 24) + : ($bytes[0] << 24) | ($bytes[1] << 16) | ($bytes[2] << 8) | $bytes[3]; + } + + public function readInt64() : int + { + if ($this->bitPosition % 8 !== 0) { + throw new InvalidArgumentException('Current position must be at byte boundary to read an int64.'); + } + + \fseek($this->handle, $this->bitPosition / 8); + $bytes = \array_values(\unpack('C*', \fread($this->handle, 8))); + $this->bitPosition += 64; + + return $this->byteOrder === ByteOrder::LITTLE_ENDIAN + ? $bytes[0] | ($bytes[1] << 8) | ($bytes[2] << 16) | ($bytes[3] << 24) + | ($bytes[4] << 32) | ($bytes[5] << 40) | ($bytes[6] << 48) | ($bytes[7] << 56) + : ($bytes[0] << 56) | ($bytes[1] << 48) | ($bytes[2] << 40) | ($bytes[3] << 32) + | ($bytes[4] << 24) | ($bytes[5] << 16) | ($bytes[6] << 8) | $bytes[7]; + } + + public function readInt96() : string + { + throw new RuntimeException('Not implemented yet.'); + } + + public function readInts32(int $total) : array + { + throw new RuntimeException('Not implemented yet.'); + } + + public function readInts64(int $total) : array + { + throw new RuntimeException('Not implemented yet.'); + } + + public function readString() : string + { + // Read the string bytes + return $this->readBytes($this->readInt32())->toString(); + } + + public function readStrings(int $total) : array + { + throw new RuntimeException('Not implemented yet.'); + } + + public function readUInt32() : int + { + if ($this->bitPosition % 8 !== 0) { + throw new InvalidArgumentException('Current position must be at byte boundary to read an uint32.'); + } + + \fseek($this->handle, $this->bitPosition / 8); + $bytes = \array_values(\unpack('C*', \fread($this->handle, 4))); + $this->bitPosition += 32; + + return $this->byteOrder === ByteOrder::LITTLE_ENDIAN + ? $bytes[0] | ($bytes[1] << 8) | ($bytes[2] << 16) | ($bytes[3] << 24) + : ($bytes[0] << 24) | ($bytes[1] << 16) | ($bytes[2] << 8) | $bytes[3]; + } + + public function readUInt64() : int + { + return $this->readInt64(); + } + + public function readUInts32(int $total) : array + { + throw new RuntimeException('Not implemented yet.'); + } + + public function readUInts64(int $total) : array + { + throw new RuntimeException('Not implemented yet.'); + } + + public function readVarInt() : int + { + $result = 0; + $shift = 0; + + do { + if ($this->bitPosition % 8 !== 0) { + throw new InvalidArgumentException('Current position must be at byte boundary to read a varint.'); + } + + \fseek($this->handle, $this->bitPosition / 8); + $byte = \ord(\fread($this->handle, 1)); + $this->bitPosition += 8; + + $result |= ($byte & 0x7F) << $shift; + $shift += 7; + } while ($byte >= 0x80); + + return $result; + } + + public function remainingLength() : DataSize + { + return new DataSize($this->length()->bits() - $this->bitPosition); + } + + public function seekBits(int $bits) : void + { + $this->bitPosition += $bits; + \fseek($this->handle, \intdiv($this->bitPosition, 8)); + } + + public function seekBytes(int $bytes) : void + { + $this->bitPosition += $bytes * 8; + \fseek($this->handle, \intdiv($this->bitPosition, 8)); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/BinaryReader/Bytes.php b/src/lib/parquet/src/Flow/Parquet/BinaryReader/Bytes.php new file mode 100644 index 000000000..11a77b33d --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/BinaryReader/Bytes.php @@ -0,0 +1,113 @@ +size = new DataSize(\count($this->bytes) * 8); + $this->iterator = new \ArrayIterator($this->bytes); + } + + public static function fromString(string $string, ByteOrder $byteOrder = ByteOrder::LITTLE_ENDIAN) : self + { + /** @phpstan-ignore-next-line */ + return new self(\array_values(\unpack('C*', $string)), $byteOrder); + } + + // Countable methods + public function count() : int + { + return \count($this->bytes); + } + + // IteratorAggregate methods + public function getIterator() : \ArrayIterator + { + return $this->iterator; + } + + // ArrayAccess methods + public function offsetExists($offset) : bool + { + return isset($this->bytes[$offset]); + } + + public function offsetGet($offset) : mixed + { + return $this->bytes[$offset]; + } + + public function offsetSet($offset, $value) : void + { + if ($offset === null) { + $this->bytes[] = $value; + } else { + $this->bytes[$offset] = $value; + } + } + + public function offsetUnset($offset) : void + { + unset($this->bytes[$offset]); + } + + /** + * @return DataSize + */ + public function size() : DataSize + { + return $this->size; + } + + /** + * @return array + */ + public function toArray() : array + { + return $this->bytes; + } + + /** + * Convert bytes to a single integer. + * + * @return int + */ + public function toInt() : int + { + $result = 0; + $bytes = $this->byteOrder === ByteOrder::LITTLE_ENDIAN ? $this->bytes : \array_reverse($this->bytes); + + foreach ($bytes as $shift => $byte) { + $result |= ($byte << ($shift * 8)); + } + + return $result; + } + + /** + * @return string + */ + public function toString() : string + { + $string = ''; + + foreach ($this->bytes as $byte) { + $string .= \pack('C', $byte); + } + + return $string; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ByteOrder.php b/src/lib/parquet/src/Flow/Parquet/ByteOrder.php new file mode 100644 index 000000000..36c7ecbef --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ByteOrder.php @@ -0,0 +1,9 @@ +bits += $bits->bits; + $this->bytes = (int) \round($this->bits / 8, 0, PHP_ROUND_HALF_DOWN); + + return; + } + + $this->bits += $bits; + $this->bytes = (int) \round($this->bits / 8, 0, PHP_ROUND_HALF_DOWN); + } + + public function bits() : int + { + return $this->bits; + } + + public function bytes() : int + { + if ($this->bytes === null) { + $this->bytes = (int) \round($this->bits / 8, 0, PHP_ROUND_HALF_DOWN); + } + + return $this->bytes; + } + + public function sub(int|self $bits) : void + { + if ($bits instanceof self) { + $this->bits -= $bits->bits; + $this->bytes = (int) \round($this->bits / 8, 0, PHP_ROUND_HALF_DOWN); + + return; + } + + $this->bits -= $bits; + $this->bytes = (int) \round($this->bits / 8, 0, PHP_ROUND_HALF_DOWN); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Exception/InvalidArgumentException.php b/src/lib/parquet/src/Flow/Parquet/Exception/InvalidArgumentException.php new file mode 100644 index 000000000..d65027234 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Exception/InvalidArgumentException.php @@ -0,0 +1,7 @@ + + */ + private array $options; + + public function __construct() + { + $this->options = [ + Option::BYTE_ARRAY_TO_STRING->name => false, + Option::ROUND_NANOSECONDS->name => false, + Option::INT_96_AS_DATETIME->name => true, + ]; + } + + public function get(Option $option) : bool + { + return $this->options[$option->name]; + } + + public function set(Option $option, bool $value = true) : self + { + $this->options[$option->name] = $value; + + return $this; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile.php new file mode 100644 index 000000000..c4e6baeba --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile.php @@ -0,0 +1,335 @@ +metadata !== null) { + return $this->metadata; + } + + $this->metadata = new Metadata($this->stream, $this->byteOrder); + + return $this->metadata; + } + + /** + * @psalm-suppress PossiblyInvalidArgument + */ + public function readChunks(Column $column, int $limit = null) : \Generator + { + $reader = new WholeChunk( + new DataBuilder($this->options, $this->logger), + new PageReader($column, $this->options, $this->byteOrder, $this->logger), + $this->logger + ); + + foreach ($this->getColumnChunks($column) as $columnChunks) { + foreach ($columnChunks as $columnChunk) { + $yieldedRows = 0; + + /** @var array $row */ + foreach ($reader->read($columnChunk, $column, $this->stream, $limit) as $row) { + yield $row; + $yieldedRows++; + + if ($limit !== null && $yieldedRows >= $limit) { + return; + } + } + } + } + } + + public function schema() : Schema + { + return $this->metadata()->schema(); + } + + /** + * @param array $columns + * + * @return \Generator> + */ + public function values(array $columns = [], int $limit = null) : \Generator + { + if (!\count($columns)) { + $columns = \array_map(static fn (Column $c) => $c->name(), $this->schema()->columns()); + } + + $this->logger->info('[Parquet File] Reading values from columns', ['columns' => $columns]); + + foreach ($columns as $columnName) { + if (!$this->metadata()->schema()->has($columnName)) { + throw new InvalidArgumentException("Column \"{$columnName}\" does not exist"); + } + } + + $rows = new \MultipleIterator(\MultipleIterator::MIT_KEYS_ASSOC); + + foreach ($columns as $columnName) { + $rows->attachIterator($this->read($this->schema()->get($columnName), $limit), $columnName); + } + + /** @var array $row */ + foreach ($rows as $row) { + yield $row; + } + } + + /** + * @return \Generator> + */ + private function getColumnChunks(Column $column) : \Generator + { + foreach ($this->metadata()->rowGroups()->all() as $rowGroup) { + $chunksInGroup = []; + + foreach ($rowGroup->columnChunks() as $columnChunk) { + if ($columnChunk->flatPath() === $column->flatPath()) { + $chunksInGroup[] = $columnChunk; + } + } + + yield $chunksInGroup; + } + } + + /** + * @psalm-suppress MixedAssignment + */ + private function read(Column $column, int $limit = null) : \Generator + { + if ($column instanceof FlatColumn) { + $this->logger->info('[Parquet File][Read Column] reading flat column', ['path' => $column->flatPath()]); + + return $this->readFlat($column, $limit); + } + + if ($column instanceof NestedColumn) { + if ($column->logicalType()?->is(LogicalType::LIST)) { + $this->logger->info('[Parquet File][Read Column] reading list', ['path' => $column->flatPath()]); + + return $this->readList($column, $limit); + } + + // Column is a map + if ($column->logicalType()?->is(LogicalType::MAP)) { + $this->logger->info('[Parquet File][Read Column] reading map', ['path' => $column->flatPath()]); + + return $this->readMap($column, $limit); + } + + $this->logger->info('[Parquet File][Read Column] reading structure', ['path' => $column->flatPath()]); + + return $this->readStruct($column, limit: $limit); + } + + throw new RuntimeException('Unknown column type'); + } + + /** + * @psalm-suppress MixedAssignment + */ + private function readFlat(FlatColumn $column, int $limit = null) : \Generator + { + return $this->readChunks($column, $limit); + } + + /** + * @psalm-suppress MixedAssignment + */ + private function readList(NestedColumn $listColumn, int $limit = null) : \Generator + { + $this->logger->debug('[Parquet File][Read Column][List]', ['column' => $listColumn->normalize()]); + $elementColumn = $listColumn->getListElement(); + + if ($elementColumn instanceof FlatColumn) { + $this->logger->info('[Parquet File][Read Column][List] reading list element as a flat column', ['path' => $elementColumn->flatPath()]); + + return $this->readFlat($elementColumn, $limit); + } + + /** @var NestedColumn $elementColumn */ + if ($elementColumn->isList()) { + $this->logger->info('[Parquet File][Read Column][List] reading list element as list', ['path' => $elementColumn->flatPath()]); + + return $this->readList($elementColumn, $limit); + } + + if ($elementColumn->isMap()) { + $this->logger->info('[Parquet File][Read Column][List] reading list element as a map', ['path' => $elementColumn->flatPath()]); + + return $this->readMap($elementColumn, $limit); + } + + $this->logger->info('[Parquet File][Read Column][List] reading list element as a structure', ['path' => $elementColumn->flatPath()]); + + return $this->readStruct($elementColumn, isCollection: true, limit: $limit); + } + + /** + * @psalm-suppress PossiblyInvalidArgument + */ + private function readMap(NestedColumn $mapColumn, int $limit = null) : \Generator + { + $this->logger->debug('[Parquet File][Read Column][Map]', ['column' => $mapColumn->normalize()]); + + $keysColumn = $mapColumn->getMapKeyElement(); + $valuesColumn = $mapColumn->getMapValueElement(); + + $keys = $this->readChunks($keysColumn, $limit); + + $values = null; + + if ($valuesColumn instanceof FlatColumn) { + $this->logger->info('[Parquet File][Read Column][Map] reading values as a flat column', ['path' => $mapColumn->flatPath()]); + $values = $this->readFlat($valuesColumn, $limit); + } + + /** @var NestedColumn $valuesColumn */ + if ($valuesColumn->isList()) { + $this->logger->info('[Parquet File][Read Column][Map] reading values as a list', ['path' => $mapColumn->flatPath()]); + $values = $this->readList($valuesColumn, $limit); + } + + if ($valuesColumn->isMap()) { + $this->logger->info('[Parquet File][Read Column][Map] reading values as a map', ['path' => $mapColumn->flatPath()]); + $values = $this->readMap($valuesColumn, $limit); + } + + if ($valuesColumn->isStruct()) { + $this->logger->info('[Parquet File][Read Column][Map] reading values as a structure', ['path' => $mapColumn->flatPath()]); + $values = $this->readStruct($valuesColumn, isCollection: true, limit: $limit); + } + + if ($values === null) { + throw new RuntimeException('Unknown column type'); + } + + $mapFlat = new \MultipleIterator(\MultipleIterator::MIT_KEYS_ASSOC); + $mapFlat->attachIterator($keys, 'keys'); + $mapFlat->attachIterator($values, 'values'); + + foreach ($mapFlat as $row) { + if ($row['keys'] === null) { + yield null; + } else { + if (\is_array($row['keys'])) { + /** + * @psalm-suppress MixedArgument + */ + yield \Flow\Parquet\array_combine_recursive($row['keys'], $row['values']); + } else { + /** + * @psalm-suppress MixedArrayOffset + */ + yield [$row['keys'] => $row['values']]; + } + } + } + } + + /** + * @param bool $isCollection - when structure is a map or list element, each struct child is a collection for example ['int' => [1, 2, 3]] instead of ['int' => 1] + * + * @psalm-suppress MixedAssignment + * @psalm-suppress MixedArgumentTypeCoercion + */ + private function readStruct(NestedColumn $structColumn, bool $isCollection = false, int $limit = null) : \Generator + { + $childrenRowsData = new \MultipleIterator(\MultipleIterator::MIT_KEYS_ASSOC); + + foreach ($structColumn->children() as $child) { + if ($child instanceof FlatColumn) { + $childrenRowsData->attachIterator($this->read($child, $limit), $child->flatPath()); + + continue; + } + + if ($child instanceof NestedColumn) { + if ($child->isList()) { + $childrenRowsData->attachIterator($this->readList($child, $limit), $child->flatPath()); + + continue; + } + + if ($child->isMap()) { + $childrenRowsData->attachIterator($this->readMap($child, $limit), $child->flatPath()); + + continue; + } + + $childrenRowsData->attachIterator($this->readStruct($child, isCollection: $isCollection, limit: $limit), $child->flatPath()); + + continue; + } + + throw new RuntimeException('Unknown column type'); + } + + $this->logger->debug('[Parquet File][Read Column][Structure]', ['column' => $structColumn->normalize()]); + + foreach ($childrenRowsData as $childrenRowData) { + if ($isCollection) { + $structsCollection = new \MultipleIterator(\MultipleIterator::MIT_KEYS_ASSOC); + + /** @var array $childColumnValue */ + foreach ($childrenRowData as $childColumnPath => $childColumnValue) { + $childColumn = $this->schema()->get($childColumnPath); + $structsCollection->attachIterator(new \ArrayIterator($childColumnValue), $childColumn->name()); + } + + $structs = []; + + foreach ($structsCollection as $structData) { + $structs[] = $structData; + } + + yield $structs; + } else { + $row = []; + + foreach ($childrenRowData as $childColumnPath => $childColumnValue) { + $childColumn = $this->schema()->get($childColumnPath); + + $row[$childColumn->name()] = $childColumnValue; + } + yield $row; + } + } + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Codec.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Codec.php new file mode 100644 index 000000000..ea482275b --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Codec.php @@ -0,0 +1,33 @@ + $data, + Compressions::SNAPPY => snappy_uncompress($data), + Compressions::GZIP => \gzdecode($data), + default => throw new RuntimeException('Compression ' . $compression->name . ' is not supported yet') + }; + + if ($result === false) { + throw new RuntimeException('Failed to decompress data'); + } + + return $result; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/ColumnChunkReader.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/ColumnChunkReader.php new file mode 100644 index 000000000..578b18c34 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/ColumnChunkReader.php @@ -0,0 +1,14 @@ +logger->debug('[Parquet File][Read Column][Read Column Chunk]', ['chunk' => $columnChunk->normalize()]); + $offset = $columnChunk->pageOffset(); + + \fseek($stream, $offset); + + if ($columnChunk->dictionaryPageOffset()) { + $dictionaryHeader = new PageHeader($stream, $offset); + $dictionary = $this->pageReader->readDictionary( + $dictionaryHeader, + $columnChunk->codec(), + $stream + ); + $offset = \ftell($stream); + } else { + $dictionary = null; + } + + $columnData = ColumnData::initialize($column); + + $rowsCount = 0; + + while (true) { + try { + /** @phpstan-ignore-next-line */ + $dataHeader = new PageHeader($stream, $offset); + } catch (TException $e) { + if ($columnData->size()) { + foreach ($this->dataBuilder->build($columnData, $column) as $row) { + $rowsCount++; + yield $row; + } + } + + break; + } + + /** There are no more pages in given column chunk */ + if ($dataHeader->compressedPageSize() === 0 || $dataHeader->type()->isDataPage() === false || ($rowsCount + $columnData->size() >= $columnChunk->rowGroup()->rowsCount())) { + if ($columnData->size()) { + /** @var array $row */ + foreach ($this->dataBuilder->build($columnData, $column) as $row) { + $rowsCount++; + yield $row; + } + } + + break; + } + + $columnData = $columnData->merge($this->pageReader->readData( + $dataHeader, + $columnChunk->codec(), + $dictionary, + $stream + )); + $offset = \ftell($stream); + + if ($offset >= $columnChunk->pageOffset() + $columnChunk->compressedSize()) { + if ($columnData->size()) { + /** @var array $row */ + foreach ($this->dataBuilder->build($columnData, $column) as $row) { + $rowsCount++; + yield $row; + } + } + + break; + } + + $splitColumnData = $columnData->splitLastRow(); + + /** @var array $row */ + foreach ($this->dataBuilder->build($splitColumnData[0], $column) as $row) { + $rowsCount++; + yield $row; + } + + $columnData = $splitColumnData[1]; + } + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/ColumnChunkReader/WholeChunk.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/ColumnChunkReader/WholeChunk.php new file mode 100644 index 000000000..7de8ce5ae --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/ColumnChunkReader/WholeChunk.php @@ -0,0 +1,85 @@ +logger->debug('[Parquet File][Read Column][Read Column Chunk]', ['chunk' => $columnChunk->normalize()]); + $offset = $columnChunk->pageOffset(); + + \fseek($stream, $offset); + + if ($columnChunk->dictionaryPageOffset()) { + $dictionaryHeader = new PageHeader($stream, $offset); + $dictionary = $this->pageReader->readDictionary( + $dictionaryHeader, + $columnChunk->codec(), + $stream + ); + $offset = \ftell($stream); + } else { + $dictionary = null; + } + + $columnData = ColumnData::initialize($column); + + $rowsToRead = $columnChunk->valuesCount(); + + if ($limit !== null && $limit < $rowsToRead) { + $rowsToRead = $limit; + } + + while (true) { + /** @phpstan-ignore-next-line */ + $dataHeader = new PageHeader($stream, $offset); + + /** There are no more pages in given column chunk */ + if ($columnData->size() >= $rowsToRead || $dataHeader->compressedPageSize() === 0 || $dataHeader->type()->isDataPage() === false) { + $yieldedRows = 0; + + /** @var array $row */ + foreach ($this->dataBuilder->build($columnData, $column) as $row) { + yield $row; + $yieldedRows++; + + if ($yieldedRows >= $rowsToRead) { + return; + } + } + + break; + } + + $columnData = $columnData->merge($this->pageReader->readData( + $dataHeader, + $columnChunk->codec(), + $dictionary, + $stream + )); + + $offset = \ftell($stream); + } + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Compressions.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Compressions.php new file mode 100644 index 000000000..e0db5ea1a --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Compressions.php @@ -0,0 +1,15 @@ + $maxValue) { + throw new InvalidArgumentException(\sprintf('Number %d is too big for %d bits', $number, $bits)); + } + + $binaryString = \str_pad(\decbin($number), $bits, '0', STR_PAD_LEFT); + + if ($bitsPerGroup <= 0) { + return $binaryString; + } + + // Split the binary string into groups of $bitsPerGroup bits + $splitBinary = \str_split($binaryString, $bitsPerGroup); + + // Join the groups with a space for readability + return \implode(' ', $splitBinary); + } + + public static function toBinary(string $bytes, int $bitsPerGroup = 8) : string + { + $binaryString = ''; + $length = \strlen($bytes); + + for ($i = 0; $i < $length; $i++) { + $byte = \ord($bytes[$i]); + $binaryString .= \str_pad(\decbin($byte), 8, '0', STR_PAD_LEFT); + } + + if ($bitsPerGroup <= 0) { + return $binaryString; + } + + $splitBinary = \str_split($binaryString, $bitsPerGroup); + + return \implode(' ', $splitBinary); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Data/DataBuilder.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Data/DataBuilder.php new file mode 100644 index 000000000..68c107d20 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Data/DataBuilder.php @@ -0,0 +1,211 @@ +logger); + + if (!$column->isList() && $column->isMap()) { + throw new RuntimeException('Flat data builder supports only flat column types, not LIST and MAP.'); + } + + foreach ($dremel->assemble($columnData->repetitions, $columnData->definitions, $columnData->values) as $value) { + yield $this->enrichData($value, $column); + } + } + + /** + * @TODO : This should be optimized by moving it into different class, checking column only once, caching it and using dedicated data transformer for values to improve performance + * + * @psalm-suppress PossiblyFalseReference + * @psalm-suppress MixedArgument + * @psalm-suppress MixedAssignment + * @psalm-suppress MixedOperand + * @psalm-suppress MixedReturnStatement + * @psalm-suppress MixedInferredReturnType + * @psalm-suppress PossiblyNullOperand + */ + private function enrichData(mixed $value, Column $column) : mixed + { + if ($column instanceof NestedColumn) { + return $value; + } + + /** @var FlatColumn $column */ + if ($value === null) { + return null; + } + + if ($column->type() === PhysicalType::INT96 && $this->options->get(Option::INT_96_AS_DATETIME)) { + if (\is_array($value) && \count($value) && !\is_array($value[0])) { + /** @psalm-suppress MixedArgumentTypeCoercion */ + return $this->nanoToDateTimeImmutable($value); + } + + if (\is_array($value)) { + $enriched = []; + + /** @var array $val */ + foreach ($value as $val) { + $enriched[] = $this->nanoToDateTimeImmutable($val); + } + + return $enriched; + } + + return $value; + } + + if ($column->logicalType()?->name() === 'DECIMAL') { + if ($column->scale() === null || $column->precision() === null) { + return $value; + } + $divisor = $column->precision() ** $column->scale(); + + if (\is_scalar($value)) { + return ((int) $value) / $divisor; + } + + if (\is_array($value)) { + $enriched = []; + + foreach ($value as $val) { + $enriched[] = $val / $divisor; + } + + return $enriched; + } + } + + if ($column->logicalType()?->name() === 'TIMESTAMP') { + /** @phpstan-ignore-next-line */ + if ($column->logicalType()?->timestamp()?->nanos() && $this->options->get(Option::ROUND_NANOSECONDS) === false) { + return $value; + } + + if (!\is_int($value) && !\is_array($value)) { + return $value; + } + + /** @phpstan-ignore-next-line */ + $isMillis = (bool) $column->logicalType()?->timestamp()?->millis(); + /** @phpstan-ignore-next-line */ + $isMicros = ($column->logicalType()?->timestamp()?->micros() || $column->logicalType()?->timestamp()?->nanos()); + + $convertValue = static function (int $val) use ($isMillis, $isMicros) : \DateTimeImmutable|int { + if ($isMillis) { + $seconds = (int) ($val / 1000); + $fraction = \str_pad((string) ($val % 1000), 3, '0', STR_PAD_LEFT) . '000'; // Pad milliseconds to microseconds + } elseif ($isMicros) { + $seconds = (int) ($val / 1000000); + $fraction = \str_pad((string) ($val % 1000000), 6, '0', STR_PAD_LEFT); + } else { + return $val; + } + + $datetime = \DateTimeImmutable::createFromFormat('U.u', \sprintf('%d.%s', $seconds, $fraction)); + + if (!$datetime) { + return $val; + } + + return $datetime; + }; + + if (\is_scalar($value)) { + return $convertValue($value); + } + + $enriched = []; + + foreach ($value as $val) { + $enriched[] = $convertValue($val); + } + + return $enriched; + } + + if ($column->logicalType()?->name() === 'DATE') { + if (\is_int($value)) { + /** @phpstan-ignore-next-line */ + return \DateTimeImmutable::createFromFormat('Y-m-d', '1970-01-01') + ->modify(\sprintf('+%d days', $value)) + ->setTime(0, 0, 0, 0); + } + + if (\is_array($value)) { + $enriched = []; + + foreach ($value as $val) { + /** @phpstan-ignore-next-line */ + $enriched[] = \DateTimeImmutable::createFromFormat('Y-m-d', '1970-01-01') + ->modify(\sprintf('+%d days', $val)) + ->setTime(0, 0, 0, 0); + } + + return $enriched; + } + } + + return $value; + } + + /** + * @psalm-suppress FalsableReturnStatement + * @psalm-suppress InvalidFalsableReturnType + * + * @param array $bytes + */ + private function nanoToDateTimeImmutable(array $bytes) : \DateTimeImmutable + { + $daysInEpoch = $bytes[8] | ($bytes[9] << 8) | ($bytes[10] << 16) | ($bytes[11] << 24); + + // Convert the first 8 bytes to the number of nanoseconds within the day + $nanosecondsWithinDay = $bytes[0] | ($bytes[1] << 8) | ($bytes[2] << 16) | ($bytes[3] << 24) | + ($bytes[4] << 32) | ($bytes[5] << 40) | ($bytes[6] << 48) | ($bytes[7] << 56); + + // The Julian epoch starts on January 1, 4713 BCE. + // The Unix epoch starts on January 1, 1970 CE. + // The number of days between these two dates is 2440588. + $daysSinceUnixEpoch = $daysInEpoch - 2440588; + + // Convert the days since the Unix epoch and the nanoseconds within the day to a Unix timestamp + $timestampSeconds = $daysSinceUnixEpoch * 86400 + $nanosecondsWithinDay / 1e9; + + // Separate the seconds and fractional seconds parts of the timestamp + $seconds = \floor($timestampSeconds); + $fraction = $timestampSeconds - $seconds; + + // Convert the fractional seconds to milliseconds + $microseconds = \round($fraction * 1e6); + + /** @phpstan-ignore-next-line */ + return \DateTimeImmutable::createFromFormat('U.u', \sprintf('%d.%06d', $seconds, $microseconds)); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Data/RLEBitPackedHybrid.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Data/RLEBitPackedHybrid.php new file mode 100644 index 000000000..4e3b984da --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Data/RLEBitPackedHybrid.php @@ -0,0 +1,131 @@ +> 1; + + if ($numGroups === 0) { + return; + } + + $count = $numGroups * 8; + $totalByteCount = (int) (($bitWidth * $count) / 8); + $remainingByteCount = $reader->remainingLength()->bytes(); + $readBytes = $reader->readBytes(\min($remainingByteCount, $totalByteCount)); + $actualByteCount = $readBytes->count(); + + $bitMask = (1 << $bitWidth) - 1; + $byteIndex = 0; + $currentByte = $readBytes[$byteIndex]; + $totalBits = $actualByteCount * 8; + $bitsLeftInByte = 8; + $bitsReadFromByte = 0; + + $resultIndex = 0; + + while ($totalBits >= $bitWidth && $resultIndex < $maxItems) { + if ($bitsReadFromByte >= 8) { + $bitsReadFromByte -= 8; + $bitsLeftInByte -= 8; + $currentByte >>= 8; + } elseif ($bitsLeftInByte - $bitsReadFromByte >= $bitWidth) { + $decodedValue = (($currentByte >> $bitsReadFromByte) & $bitMask); + $totalBits -= $bitWidth; + $bitsReadFromByte += $bitWidth; + $resultIndex++; + $output[] = $decodedValue; + } elseif ($byteIndex + 1 < $actualByteCount) { + $byteIndex += 1; + $currentByte |= ($readBytes[$byteIndex] << $bitsLeftInByte); + $bitsLeftInByte += 8; + } + } + } + + public function decodeHybrid(BinaryReader $reader, int $bitWidth, int $maxItems, DataSize $length = null) : array + { + $length = ($length) ?: new DataSize($reader->readInt32() * 8); + + $output = []; + $start = $reader->position(); + + $iteration = 0; + + while (($reader->position()->bytes() - $start->bytes()) < $length->bytes() && \count($output) < $maxItems) { + $iteration++; + $varInt = $reader->readVarInt(); + $isRle = ($varInt & 1) === 0; + + $this->debugLog($iteration, $varInt, $isRle, $bitWidth, $length, $reader, $output); + + if ($isRle) { + $this->decodeRLE($reader, $bitWidth, $varInt, $maxItems - \count($output), $output); + } else { + $this->decodeBitPacked($reader, $bitWidth, $varInt, $maxItems - \count($output), $output); + } + } + + return \array_slice($output, 0, $maxItems); + } + + public function decodeRLE(BinaryReader $reader, int $bitWidth, int $intVar, int $maxItems, array &$output) : void + { + $isLiteralRun = $intVar & 1; + $runLength = $intVar >> 1; + + if ($runLength === 0) { + return; + } + + $count = \min($runLength, $maxItems); + $width = (int) (($bitWidth + 7) / 8); + $value = $width > 0 ? $reader->readBytes($width)->toInt() : 0; + + if ($isLiteralRun) { + for ($i = 0; $i < $count; $i++) { + $output[] = $reader->readBits($bitWidth); + } + } else { + for ($i = 0; $i < $count; $i++) { + $output[] = $value; + } + } + } + + private function debugLog(int $iteration, int $varInt, bool $isRle, int $bitWidth, DataSize $length, BinaryReader $reader, array $output) : void + { + if ($this->logger instanceof NullLogger) { + return; + } + + $this->logger->debug('RLE/BytePacked hybrid decoding', [ + 'iteration' => $iteration, + 'var_int' => $varInt, + 'is_rle' => $isRle, + 'bit_width' => $bitWidth, + 'length' => ['bits' => $length->bits(), 'bytes' => $length->bytes()], + 'reader_position' => ['bits' => $reader->position()->bits(), 'bytes' => $reader->position()->bytes()], + 'output_count' => \count($output), + ]); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/DataCoder.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/DataCoder.php new file mode 100644 index 000000000..5b19249af --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/DataCoder.php @@ -0,0 +1,243 @@ +byteOrder); + $this->debugDecodeData($buffer, $encoding, $physicalType, $logicalType, $expectedValuesCount, $maxRepetitionsLevel, $maxDefinitionsLevel); + + $RLEBitPackedHybrid = new RLEBitPackedHybrid($this->logger); + + if ($maxRepetitionsLevel) { + $this->debugLogRepetitions($maxRepetitionsLevel, $reader); + $repetitions = $this->readRLEBitPackedHybrid($reader, $RLEBitPackedHybrid, $this->bitWithFrom($maxRepetitionsLevel), $expectedValuesCount); + } else { + $repetitions = []; + } + + if ($maxDefinitionsLevel) { + $this->debugLogDefinitions($maxDefinitionsLevel, $reader); + $definitions = $this->readRLEBitPackedHybrid($reader, $RLEBitPackedHybrid, $this->bitWithFrom($maxDefinitionsLevel), $expectedValuesCount); + } else { + $definitions = []; + } + + $nullsCount = \count($definitions) ? \count(\array_filter($definitions, fn ($definition) => $definition === 0)) : 0; + + if ($encoding === Encodings::PLAIN) { + $this->debugLogPlainEncoding($expectedValuesCount, $nullsCount); + + $total = $expectedValuesCount - $nullsCount; + + $rawValues = match ($physicalType) { + PhysicalType::INT32 => $reader->readInts32($total), + PhysicalType::INT64 => $reader->readInts64($total), + PhysicalType::INT96 => $reader->readInts96($total), + PhysicalType::FLOAT => $reader->readFloats($total), + PhysicalType::DOUBLE => $reader->readDoubles($total), + PhysicalType::BYTE_ARRAY => match ($logicalType?->name()) { + LogicalType::STRING => $reader->readStrings($total), + default => match ($this->options->get(Option::BYTE_ARRAY_TO_STRING)) { + true => $reader->readStrings($total), + false => $reader->readByteArrays($total) + } + }, + PhysicalType::FIXED_LEN_BYTE_ARRAY => (array) \unpack('H*', $buffer), + PhysicalType::BOOLEAN => $reader->readBooleans($total), + }; + + return new ColumnData($physicalType, $logicalType, $repetitions, $definitions, $rawValues); + } + + if ($encoding === Encodings::RLE_DICTIONARY || $encoding === Encodings::PLAIN_DICTIONARY) { + $this->debugLogDictionaryEncoding($expectedValuesCount, $nullsCount); + + if (\count($definitions)) { + $bitWidth = $reader->readBytes(1)->toInt(); + $this->logger->debug('Decoding indices', []); + + /** @var array $indices */ + $indices = $this->readRLEBitPackedHybrid( + $reader, + $RLEBitPackedHybrid, + $bitWidth, + $expectedValuesCount - $nullsCount, + $reader->remainingLength() + ); + + /** @var array $values */ + $values = []; + + foreach ($indices as $index) { + /** @psalm-suppress MixedAssignment */ + $values[] = $dictionary?->values[$index]; + } + } else { + $values = []; + } + + return new ColumnData($physicalType, $logicalType, $repetitions, $definitions, $values); + } + + throw new RuntimeException('Encoding ' . $encoding->name . ' not supported'); + } + + public function decodeDictionary(string $buffer, PhysicalType $physicalType, ?LogicalType $logicalType, Encodings $encoding, int $expectedValuesCount) : Dictionary + { + $reader = new BinaryBufferReader($buffer, $this->byteOrder); + $this->debugLogDictionaryDecode($buffer, $encoding, $physicalType); + + $rawValues = match ($physicalType) { + PhysicalType::INT32 => $reader->readInts32($expectedValuesCount), + PhysicalType::INT64 => $reader->readInts64($expectedValuesCount), + PhysicalType::INT96 => $reader->readInts96($expectedValuesCount), + PhysicalType::FLOAT => $reader->readFloats($expectedValuesCount), + PhysicalType::DOUBLE => $reader->readDoubles($expectedValuesCount), + PhysicalType::BYTE_ARRAY => match ($logicalType?->name()) { + LogicalType::STRING => $reader->readStrings($expectedValuesCount), + default => match ($this->options->get(Option::BYTE_ARRAY_TO_STRING)) { + true => $reader->readStrings($expectedValuesCount), + false => $reader->readByteArrays($expectedValuesCount) + } + }, + PhysicalType::FIXED_LEN_BYTE_ARRAY => (array) \unpack('H*', $buffer), + PhysicalType::BOOLEAN => $reader->readBooleans($expectedValuesCount), + }; + + return new Dictionary($rawValues); + } + + private function bitWithFrom(int $value) : int + { + return (int) \ceil(\log($value + 1, 2)); + } + + private function debugDecodeData(string $buffer, Encodings $encoding, PhysicalType $physicalType, ?LogicalType $logicalType, int $expectedValuesCount, int $maxRepetitionsLevel, int $maxDefinitionsLevel) : void + { + if ($this->logger instanceof NullLogger) { + return; + } + + $this->logger->debug('Decoding data', [ + 'buffer_length' => \strlen($buffer), + 'encoding' => $encoding->name, + 'physical_type' => $physicalType->name, + 'logical_type' => $logicalType?->name(), + 'expected_values_count' => $expectedValuesCount, + 'max_repetitions_level' => $maxRepetitionsLevel, + 'max_definitions_level' => $maxDefinitionsLevel, + ]); + } + + private function debugLogDefinitions(int $maxDefinitionsLevel, BinaryBufferReader $reader) : void + { + if ($this->logger instanceof NullLogger) { + return; + } + + $this->logger->debug('Decoding definitions', ['max_definitions_level' => $maxDefinitionsLevel, 'reader_position' => ['bits' => $reader->position()->bits(), 'bytes' => $reader->position()->bytes()]]); + } + + private function debugLogDictionaryDecode(string $buffer, Encodings $encoding, PhysicalType $physicalType) : void + { + if ($this->logger instanceof NullLogger) { + return; + } + + $this->logger->debug('Decoding dictionary', [ + 'buffer_length' => \strlen($buffer), + 'encoding' => $encoding->name, + 'physical_type' => $physicalType->name, + ]); + } + + private function debugLogDictionaryEncoding(int $expectedValuesCount, int $nullsCount) : void + { + if ($this->logger instanceof NullLogger) { + return; + } + + $this->logger->debug('Decoding RLE_DICTIONARY/PLAIN_DICTIONARY values', ['not_nullable_values_count' => $expectedValuesCount - $nullsCount, 'nulls_count' => $nullsCount]); + } + + private function debugLogPlainEncoding(int $expectedValuesCount, int $nullsCount) : void + { + if ($this->logger instanceof NullLogger) { + return; + } + + $this->logger->debug('Decoding PLAIN values', ['not_nullable_values_count' => $expectedValuesCount - $nullsCount, 'nulls_count' => $nullsCount]); + } + + private function debugLogRepetitions(int $maxRepetitionsLevel, BinaryBufferReader $reader) : void + { + if ($this->logger instanceof NullLogger) { + return; + } + + $this->logger->debug('Decoding repetitions', ['max_repetitions_level' => $maxRepetitionsLevel, 'reader_position' => ['bits' => $reader->position()->bits(), 'bytes' => $reader->position()->bytes()]]); + } + + private function debugLogRLEBitPackedHybridPost(array $data) : void + { + if ($this->logger instanceof NullLogger) { + return; + } + + $this->logger->debug('Decoded data', ['data_count' => \count($data), 'data' => $data]); + } + + private function debugLogRLEBitPackedHybridPre(int $bitWidth, int $expectedValuesCount, BinaryBufferReader $reader) : void + { + if ($this->logger instanceof NullLogger) { + return; + } + + $this->logger->debug('Decoding data with RLE Hybrid', ['bitWidth' => $bitWidth, 'expected_values_count' => $expectedValuesCount, 'reader_position' => ['bits' => $reader->position()->bits(), 'bytes' => $reader->position()->bytes()]]); + } + + private function readRLEBitPackedHybrid(BinaryBufferReader $reader, RLEBitPackedHybrid $RLEBitPackedHybrid, int $bitWidth, int $expectedValuesCount, DataSize $length = null) : array + { + $this->debugLogRLEBitPackedHybridPre($bitWidth, $expectedValuesCount, $reader); + $data = ($RLEBitPackedHybrid)->decodeHybrid($reader, $bitWidth, $expectedValuesCount, $length); + $this->debugLogRLEBitPackedHybridPost($data); + + return $data; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Encodings.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Encodings.php new file mode 100644 index 000000000..0e2bb4582 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Encodings.php @@ -0,0 +1,16 @@ +value, \fread($stream, 4))[1]; + \fseek($stream, -($metadataLength + 8), SEEK_END); + + $this->metaData = new FileMetaData(); + $this->metaData->read(new TCompactProtocol(new TStreamTransport($stream, $stream))); + } + + public function createdBy() : ?string + { + return $this->metaData()->created_by; + } + + public function rowGroups() : RowGroups + { + return new RowGroups($this->metaData()->row_groups); + } + + public function rowsNumber() : int + { + return $this->metaData()->num_rows; + } + + public function schema() : Schema + { + if ($this->schema === null) { + $this->schema = new Schema($this->metadata()->schema); + } + + return $this->schema; + } + + public function version() : int + { + return $this->metaData()->version; + } + + private function metadata() : FileMetaData + { + return $this->metaData; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/ColumnData.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/ColumnData.php new file mode 100644 index 000000000..02c47df28 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/ColumnData.php @@ -0,0 +1,159 @@ + $repetitions + * @param array $definitions + * @param array $values + */ + public function __construct( + public readonly PhysicalType $type, + public readonly ?LogicalType $logicalType, + public readonly array $repetitions, + public readonly array $definitions, + public readonly array $values + ) { + } + + public static function initialize(Column $column) : self + { + return new self($column->type(), $column->logicalType(), [], [], []); + } + + public function isEmpty() : bool + { + return \count($this->definitions) === 0 && \count($this->values) === 0; + } + + public function merge(self $columnData) : self + { + if ($columnData->type !== $this->type) { + throw new \LogicException('Column data type mismatch, expected ' . $this->type->name . ', got ' . $columnData->type->name); + } + + if ($this->logicalType?->name() !== $columnData->logicalType?->name()) { + /** @psalm-suppress PossiblyNullOperand */ + throw new \LogicException('Column data logical type mismatch, expected ' . $this->logicalType?->name() . ', got ' . $columnData->logicalType?->name()); + } + + return new self( + $this->type, + $this->logicalType, + \array_merge($this->repetitions, $columnData->repetitions), + \array_merge($this->definitions, $columnData->definitions), + \array_merge($this->values, $columnData->values), + ); + } + + public function normalize() : array + { + return [ + 'type' => $this->type->name, + 'logical_type' => $this->logicalType?->name(), + 'repetitions_count' => \count($this->repetitions), + 'repetitions' => $this->repetitions, + 'definitions_count' => \count($this->definitions), + 'definitions' => $this->definitions, + 'values_count' => \count($this->values), + 'values' => $this->values, + ]; + } + + public function size() : int + { + if (!\count($this->definitions)) { + return \count($this->values); + } + + return \count($this->definitions); + } + + /** + * @psalm-suppress MixedAssignment + * @psalm-suppress MixedArgumentTypeCoercion + * @psalm-suppress ArgumentTypeCoercion + * + * @return array{0: self, 1: self} + */ + public function splitLastRow() : array + { + if (!\count($this->repetitions)) { + return [$this, new self($this->type, $this->logicalType, [], [], [])]; + } + + $repetitions = []; + $definitions = []; + $values = []; + + $maxDefinition = \max($this->definitions); + + $lastRowRepetitions = []; + $lastRowDefinitions = []; + $lastRowValues = []; + $valueIndex = 0; + + foreach ($this->repetitions as $index => $repetition) { + $definition = $this->definitions[$index]; + + if ($repetition === 0 && !\count($lastRowRepetitions)) { + $lastRowRepetitions[] = $repetition; + $lastRowDefinitions[] = $definition; + + if ($definition === $maxDefinition) { + $lastRowValues[] = $this->values[$valueIndex]; + $valueIndex++; + } + + continue; + } + + if ($repetition === 0) { + $repetitions = \array_merge($repetitions, $lastRowRepetitions); + $definitions = \array_merge($definitions, $lastRowDefinitions); + $values = \array_merge($values, $lastRowValues); + + $lastRowRepetitions = [$repetition]; + $lastRowDefinitions = [$definition]; + + if ($definition === $maxDefinition) { + $lastRowValues = [$this->values[$valueIndex]]; + $valueIndex++; + } else { + $lastRowValues = []; + } + + continue; + } + + $lastRowRepetitions[] = $repetition; + $lastRowDefinitions[] = $definition; + + if ($definition === $maxDefinition) { + $lastRowValues[] = $this->values[$valueIndex]; + $valueIndex++; + } + } + + $currentValues = $this->values; + + if (\count($lastRowValues) === 0) { + $lastRowValues = []; + } else { + $lastRowValues = \array_splice($currentValues, -\count($lastRowValues)); + } + + return [ + new self($this->type, $this->logicalType, $repetitions, $definitions, $values), + new self($this->type, $this->logicalType, $lastRowRepetitions, $lastRowDefinitions, $lastRowValues), + ]; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Dictionary.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Dictionary.php new file mode 100644 index 000000000..4cd899f3a --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Dictionary.php @@ -0,0 +1,10 @@ +dataPageHeader->encoding); + } + + public function valuesCount() : int + { + return $this->dataPageHeader->num_values; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Header/DataPageHeaderV2.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Header/DataPageHeaderV2.php new file mode 100644 index 000000000..9cef4b08f --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Header/DataPageHeaderV2.php @@ -0,0 +1,21 @@ +dataPageHeaderV2->encoding); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Header/DictionaryPageHeader.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Header/DictionaryPageHeader.php new file mode 100644 index 000000000..730ef2db3 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Header/DictionaryPageHeader.php @@ -0,0 +1,26 @@ +dictionaryPageHeader->encoding); + } + + public function valuesCount() : int + { + return $this->dictionaryPageHeader->num_values; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Header/Type.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Header/Type.php new file mode 100644 index 000000000..63ae3c25a --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/Header/Type.php @@ -0,0 +1,16 @@ +value === self::DATA_PAGE->value; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/PageHeader.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/PageHeader.php new file mode 100644 index 000000000..c980a08e1 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Page/PageHeader.php @@ -0,0 +1,136 @@ +read($protocol); + + $this->pageHeader = $pageHeader; + + if ($pageHeader->data_page_header !== null) { + $this->dataPageHeader = new DataPageHeader($pageHeader->data_page_header); + } + + if ($pageHeader->data_page_header_v2 !== null) { + $this->dataPageHeaderV2 = new DataPageHeaderV2($pageHeader->data_page_header_v2); + } + + if ($pageHeader->dictionary_page_header !== null) { + $this->dictionaryPageHeader = new DictionaryPageHeader($pageHeader->dictionary_page_header); + } + } + + /** + * @psalm-suppress RedundantCastGivenDocblockType + */ + public function compressedPageSize() : int + { + return (int) $this->pageHeader->compressed_page_size; + } + + public function dataPageHeader() : ?DataPageHeader + { + return $this->dataPageHeader; + } + + public function dataPageHeaderV2() : ?DataPageHeaderV2 + { + return $this->dataPageHeaderV2; + } + + /** + * @psalm-suppress NullPropertyFetch + * @psalm-suppress RedundantConditionGivenDocblockType + * @psalm-suppress RedundantCastGivenDocblockType + * @psalm-suppress RedundantConditionGivenDocblockType + * @psalm-suppress MixedInferredReturnType + */ + public function dataValuesCount() : ?int + { + if ($this->pageHeader->data_page_header !== null) { + return (int) $this->pageHeader->data_page_header->num_values; + } + + if ($this->pageHeader->data_page_header_v2 !== null) { + return (int) $this->pageHeader->data_page_header->num_values; + } + + return null; + } + + public function dictionaryPageHeader() : ?DictionaryPageHeader + { + return $this->dictionaryPageHeader; + } + + /** + * @psalm-suppress RedundantCastGivenDocblockType + * @psalm-suppress RedundantConditionGivenDocblockType + */ + public function dictionaryValuesCount() : ?int + { + if ($this->pageHeader->dictionary_page_header !== null) { + return (int) $this->pageHeader->dictionary_page_header->num_values; + } + + return null; + } + + public function encoding() : Encodings + { + if ($this->pageHeader->type === Type::DICTIONARY_PAGE->value) { + return Encodings::from($this->pageHeader->dictionary_page_header->encoding); + } + + if ($this->pageHeader->type === Type::DATA_PAGE_V2->value) { + return Encodings::from($this->pageHeader->data_page_header_v2->encoding); + } + + return Encodings::from($this->pageHeader->data_page_header->encoding); + } + + public function normalize() : array + { + return [ + 'type' => $this->type()->name, + 'dictionary_values_count' => $this->dictionaryValuesCount(), + 'data_values_count' => $this->dataValuesCount(), + 'encoding' => $this->encoding()->name, + 'compressed_page_size' => $this->compressedPageSize(), + ]; + } + + public function type() : Type + { + return Type::from($this->pageHeader->type); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/PageReader.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/PageReader.php new file mode 100644 index 000000000..0f6100247 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/PageReader.php @@ -0,0 +1,79 @@ +options, $this->byteOrder, $this->logger)) + ->decodeData( + (new Codec()) + ->decompress( + /** @phpstan-ignore-next-line */ + \fread($stream, $pageHeader->compressedPageSize()), + $codec + ), + /** @phpstan-ignore-next-line */ + $pageHeader->dataPageHeader()->encoding(), + $this->column->type(), + $this->column->logicalType(), + /** @phpstan-ignore-next-line */ + $pageHeader->dataPageHeader()->valuesCount(), + $this->column->maxRepetitionsLevel(), + $this->column->maxDefinitionsLevel(), + $dictionary + ); + } + + /** + * @param resource $stream + */ + public function readDictionary(PageHeader $pageHeader, Compressions $codec, $stream) : Dictionary + { + if (!$pageHeader->dictionaryPageHeader()) { + throw new RuntimeException("Can't read dictionary from non dictionary page header"); + } + + return (new DataCoder($this->options, $this->byteOrder, $this->logger)) + ->decodeDictionary( + (new Codec()) + ->decompress( + /** + * @phpstan-ignore-next-line + * + * @psalm-suppress MixedArgument + */ + \fread($stream, $pageHeader->compressedPageSize()), + $codec + ), + $this->column->type(), + $this->column->logicalType(), + $pageHeader->dictionaryPageHeader()->encoding(), + $pageHeader->dictionaryPageHeader()->valuesCount(), + ); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroup.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroup.php new file mode 100644 index 000000000..14e0ebabb --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroup.php @@ -0,0 +1,25 @@ + + */ + public function columnChunks() : array + { + return \array_map(fn (\Flow\Parquet\Thrift\ColumnChunk $columnChunk) => new ColumnChunk($columnChunk, $this), $this->rowGroup->columns); + } + + public function rowsCount() : int + { + return $this->rowGroup->num_rows; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroup/ColumnChunk.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroup/ColumnChunk.php new file mode 100644 index 000000000..4d3b9c79e --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroup/ColumnChunk.php @@ -0,0 +1,136 @@ +normalize(); + } + + public function codec() : Compressions + { + return Compressions::from($this->columnChunk->meta_data->codec); + } + + public function compressedSize() : int + { + return $this->columnChunk->meta_data->total_compressed_size; + } + + public function dataPageOffset() : int + { + return $this->columnChunk->meta_data->data_page_offset; + } + + public function dictionaryPageOffset() : ?int + { + return $this->columnChunk->meta_data->dictionary_page_offset; + } + + /** + * @return array + */ + public function encodings() : array + { + return \array_map(static fn ($encoding) => Encodings::from($encoding), $this->columnChunk->meta_data->encodings); + } + + public function fileOffset() : int + { + return $this->columnChunk->file_offset; + } + + public function flatPath() : string + { + return \implode('.', $this->columnChunk->meta_data->path_in_schema); + } + + public function indexPageOffset() : ?int + { + return $this->columnChunk->meta_data->index_page_offset; + } + + public function normalize() : array + { + return [ + 'file_offset' => $this->fileOffset(), + 'meta_data' => [ + 'flat_path' => $this->flatPath(), + 'type' => $this->type()->name, + 'encodings' => \array_map(static fn (Encodings $encoding) => $encoding->name, $this->encodings()), + 'codec' => $this->codec()->name, + 'row_group' => [ + 'num_rows' => $this->rowGroup->rowsCount(), + ], + 'num_values' => $this->valuesCount(), + 'total_uncompressed_size' => $this->columnChunk->meta_data->total_uncompressed_size, + 'total_compressed_size' => $this->columnChunk->meta_data->total_compressed_size, + 'data_page_offset' => $this->columnChunk->meta_data->data_page_offset, + 'index_page_offset' => $this->columnChunk->meta_data->index_page_offset, + 'dictionary_page_offset' => $this->columnChunk->meta_data->dictionary_page_offset, + 'statistics' => $this->columnChunk->meta_data->statistics, + ], + ]; + } + + /** + * @psalm-suppress ArgumentTypeCoercion + */ + public function pageOffset() : int + { + $offset = \min( + \array_filter( + [ + $this->columnChunk->meta_data->dictionary_page_offset, + $this->columnChunk->meta_data->data_page_offset, + $this->columnChunk->meta_data->index_page_offset, + ], + ) + ); + + return $offset; + } + + public function rootName() : string + { + return $this->columnChunk->meta_data->path_in_schema[0]; + } + + public function rowGroup() : RowGroup + { + return $this->rowGroup; + } + + public function statistics() : Statistics + { + return new Statistics($this->columnChunk->meta_data->statistics); + } + + public function totalCompressedSize() : int + { + return $this->columnChunk->meta_data->total_compressed_size; + } + + public function type() : PhysicalType + { + return PhysicalType::from($this->columnChunk->meta_data->type); + } + + public function valuesCount() : int + { + return $this->columnChunk->meta_data->num_values; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroup/Statistics.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroup/Statistics.php new file mode 100644 index 000000000..2d9727d11 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroup/Statistics.php @@ -0,0 +1,19 @@ +statistics->null_count ?? null; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroups.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroups.php new file mode 100644 index 000000000..56f38fd5b --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/RowGroups.php @@ -0,0 +1,33 @@ + + */ + private readonly array $rowGroups; + + /** + * @param array<\Flow\Parquet\Thrift\RowGroup> $rowGroups + */ + public function __construct(array $rowGroups) + { + $groups = []; + + foreach ($rowGroups as $rowGroup) { + $groups[] = new RowGroup($rowGroup); + } + + $this->rowGroups = $groups; + } + + /** + * @return array + */ + public function all() : array + { + return $this->rowGroups; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema.php new file mode 100644 index 000000000..2a399a387 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema.php @@ -0,0 +1,196 @@ + + */ + private array $cache = []; + + /** + * @var array + */ + private readonly array $columns; + + private readonly SchemaElement $schemaRoot; + + /** + * @param array $schemaElements + */ + public function __construct(array $schemaElements) + { + if (!\count($schemaElements)) { + throw new \InvalidArgumentException('Schema must have at least one element'); + } + + /** @phpstan-ignore-next-line */ + $this->schemaRoot = \array_shift($schemaElements); + $this->columns = $this->processSchema($schemaElements); + } + + /** + * @return array + */ + public function columns() : array + { + return $this->columns; + } + + public function get(string $flatPath) : Column + { + if (\array_key_exists($flatPath, $this->cache)) { + return $this->cache[$flatPath]; + } + + $getByFlatPath = static function (string $flatPath, array $columns) use (&$getByFlatPath) : ?Column { + /** @var Column $column */ + foreach ($columns as $column) { + if ($column instanceof FlatColumn) { + if ($column->flatPath() === $flatPath) { + return $column; + } + } else { + /** @var NestedColumn $column */ + if ($column->flatPath() === $flatPath) { + return $column; + } + + /** + * @var null|NestedColumn $nestedColumn + * + * @psalm-suppress MixedFunctionCall + */ + $nestedColumn = $getByFlatPath($flatPath, $column->children()); + + if ($nestedColumn !== null) { + return $nestedColumn; + } + } + } + + return null; + }; + + $column = $getByFlatPath($flatPath, $this->columns); + + if ($column instanceof Column) { + $this->cache[$flatPath] = $column; + + return $this->cache[$flatPath]; + } + + throw new InvalidArgumentException("Column \"{$flatPath}\" does not exist"); + } + + public function has(string $name) : bool + { + try { + $this->get($name); + + return true; + } catch (InvalidArgumentException $e) { + return false; + } + } + + public function toDDL() : array + { + return [$this->schemaRoot->name => [ + 'type' => 'message', + 'children' => $this->generateDDL($this->columns), + ]]; + } + + /** + * @param array $columns + */ + private function generateDDL(array $columns) : array + { + $ddlArray = []; + + foreach ($columns as $column) { + $ddlArray[$column->name()] = $column->ddl(); + } + + return $ddlArray; + } + + /** + * @param array $schemaElements + * + * @return array + */ + private function processSchema( + array $schemaElements, + int &$index = 0, + ?string $rootPath = null, + int $maxDefinitionLevel = 0, + int $maxRepetitionLevel = 0, + int $childrenCount = null, + Column $parent = null + ) : array { + $columns = []; + + $processed_children = 0; + + while ($index < \count($schemaElements) && ($childrenCount === null || $processed_children < $childrenCount)) { + $elem = $schemaElements[$index]; + $index++; + + $currentMaxDefLevel = $maxDefinitionLevel; + $currentMaxRepLevel = $maxRepetitionLevel; + + // Update maxDefinitionLevel and maxRepetitionLevel based on the repetition type of the current element + if ($elem->repetition_type !== Repetition::REQUIRED->value) { + $currentMaxDefLevel++; + } + + if ($elem->repetition_type === Repetition::REPEATED->value) { + $currentMaxRepLevel++; + } + + $root = new FlatColumn($elem, $currentMaxDefLevel, $currentMaxRepLevel, $rootPath, $parent); + + if ($elem->num_children > 0) { + $nestedColumn = new NestedColumn($root, [], $currentMaxDefLevel, $currentMaxRepLevel, $parent); // create NestedColumn with empty children first + $children = $this->processSchema( + $schemaElements, + $index, + $root->flatPath(), + $currentMaxDefLevel, + $currentMaxRepLevel, + $elem->num_children, + $nestedColumn // pass the NestedColumn as the parent + ); + + // now update the children of the NestedColumn + $nestedColumn->setChildren($children); + + $nestedMaxDefLevel = $currentMaxDefLevel; + $nestedMaxRepLevel = $currentMaxRepLevel; + + foreach ($children as $child) { + $nestedMaxDefLevel = \max($nestedMaxDefLevel, $child->maxDefinitionsLevel()); + $nestedMaxRepLevel = \max($nestedMaxRepLevel, $child->maxRepetitionsLevel()); + } + + $columns[] = $nestedColumn; // use the updated NestedColumn + } else { + $columns[] = $root; + } + + $processed_children++; + } + + return $columns; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/Column.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/Column.php new file mode 100644 index 000000000..1ba223eb9 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/Column.php @@ -0,0 +1,38 @@ +type = PhysicalType::from((int) $this->schemaElement->type); + $this->logicalType = $this->schemaElement->logicalType === null ? null : new LogicalType($this->schemaElement->logicalType); + } + + public function __debugInfo() : ?array + { + return $this->normalize(); + } + + /** @psalm-suppress PossiblyNullOperand */ + public function ddl() : array + { + return [ + /** @phpstan-ignore-next-line */ + 'type' => $this->type()->name . ($this->logicalType()?->name() !== null ? ' (' . $this->logicalType()?->name() . ')' : ''), + 'optional' => $this->repetition()?->value === Repetition::OPTIONAL->value, + ]; + } + + public function flatPath() : string + { + if ($this->rootPath !== null) { + return $this->rootPath . '.' . $this->schemaElement->name; + } + + return $this->schemaElement->name; + } + + public function isList() : bool + { + return false; + } + + public function isListElement() : bool + { + if ($this->parent !== null) { + // element + if ($this->parent->logicalType()?->name() === 'LIST') { + return true; + } + + // list.element + if ($this->parent->parent()?->logicalType()?->name() === 'LIST') { + return true; + } + + // list.element.{column} + if ($this->parent->parent()?->parent()?->logicalType()?->name() === 'LIST') { + return true; + } + } + + return false; + } + + public function isMap() : bool + { + return false; + } + + public function isMapElement() : bool + { + if ($this->parent === null) { + return false; + } + + if ($this->parent()?->logicalType()?->name() === 'MAP') { + return true; + } + + if ($this->parent()?->parent()?->logicalType()?->name() === 'MAP') { + return true; + } + + if ($this->parent()?->parent()?->parent()?->logicalType()?->name() === 'MAP') { + return true; + } + + return false; + } + + public function isStruct() : bool + { + return false; + } + + public function isStructElement() : bool + { + $parent = $this->parent(); + + if ($parent === null) { + return false; + } + + /** @var NestedColumn $parent */ + if ($parent->isList()) { + return false; + } + + if ($parent->isMap()) { + return false; + } + + return true; + } + + public function logicalType() : ?LogicalType + { + return $this->logicalType; + } + + public function maxDefinitionsLevel() : int + { + return $this->maxDefinitionsLevel; + } + + public function maxRepetitionsLevel() : int + { + return $this->maxRepetitionsLevel; + } + + public function name() : string + { + return $this->schemaElement->name; + } + + public function normalize() : array + { + return [ + 'type' => 'flat', + 'name' => $this->name(), + 'flat_path' => $this->flatPath(), + 'physical_type' => $this->type()->name, + 'logical_type' => $this->logicalType()?->name(), + 'repetition' => $this->repetition()?->name, + 'precision' => $this->precision(), + 'scale' => $this->scale(), + 'max_definition_level' => $this->maxDefinitionsLevel, + 'max_repetition_level' => $this->maxRepetitionsLevel, + 'children' => null, + 'is_map' => $this->isMap(), + 'is_list' => $this->isList(), + 'is_struct' => $this->isStruct(), + 'is_list_element' => $this->isListElement(), + 'is_map_element' => $this->isMapElement(), + 'is_struct_element' => $this->isStructElement(), + ]; + } + + public function parent() : ?Column + { + return $this->parent; + } + + public function precision() : ?int + { + return $this->schemaElement->precision; + } + + public function repetition() : ?Repetition + { + return Repetition::from($this->schemaElement->repetition_type); + } + + public function scale() : ?int + { + return $this->schemaElement->scale; + } + + public function type() : PhysicalType + { + return $this->type; + } + + public function typeLength() : ?int + { + return $this->schemaElement->type_length; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/LogicalType.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/LogicalType.php new file mode 100644 index 000000000..0a2d5aeca --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/LogicalType.php @@ -0,0 +1,121 @@ +name() === $logicalType; + } + + /** + * @psalm-suppress RedundantConditionGivenDocblockType + */ + public function name() : string + { + if ($this->logicalType->STRING !== null) { + return self::STRING; + } + + if ($this->logicalType->MAP !== null) { + return self::MAP; + } + + if ($this->logicalType->LIST !== null) { + return self::LIST; + } + + if ($this->logicalType->ENUM !== null) { + return self::ENUM; + } + + if ($this->logicalType->DECIMAL !== null) { + return self::DECIMAL; + } + + if ($this->logicalType->DATE !== null) { + return self::DATE; + } + + if ($this->logicalType->TIME !== null) { + return self::TIME; + } + + if ($this->logicalType->TIMESTAMP !== null) { + return self::TIMESTAMP; + } + + if ($this->logicalType->INTEGER !== null) { + return self::INTEGER; + } + + if ($this->logicalType->UNKNOWN !== null) { + return self::UNKNOWN; + } + + if ($this->logicalType->JSON !== null) { + return self::JSON; + } + + if ($this->logicalType->BSON !== null) { + return self::BSON; + } + + if ($this->logicalType->UUID !== null) { + return self::UUID; + } + + throw new \InvalidArgumentException('Unknown logical type'); + } + + public function timestamp() : ?Timestamp + { + if ($this->logicalType->TIMESTAMP === null) { + return null; + } + + if ($this->timestamp === null) { + $this->timestamp = new Timestamp($this->logicalType->TIMESTAMP); + } + + return $this->timestamp; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/LogicalType/TimeUnit.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/LogicalType/TimeUnit.php new file mode 100644 index 000000000..c7591f307 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/LogicalType/TimeUnit.php @@ -0,0 +1,10 @@ +timestampType->isAdjustedToUTC; + } + + public function micros() : bool + { + return $this->timestampType->unit->MICROS !== null; + } + + public function millis() : bool + { + return $this->timestampType->unit->MILLIS !== null; + } + + public function nanos() : bool + { + return $this->timestampType->unit->NANOS !== null; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/NestedColumn.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/NestedColumn.php new file mode 100644 index 000000000..7d47624e4 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/NestedColumn.php @@ -0,0 +1,263 @@ + + */ + private array $children; + + /** + * @param array $columns + */ + public function __construct( + private readonly FlatColumn $root, + array $columns, + private readonly int $maxDefinitionsLevel, + private readonly int $maxRepetitionsLevel, + private ?Column &$parent = null + ) { + $this->children = $columns; + } + + public function __debugInfo() : ?array + { + return $this->normalize(); + } + + /** + * @return array + */ + public function children() : array + { + return $this->children; + } + + public function ddl() : array + { + $ddlArray = [ + 'type' => 'group', + 'optional' => $this->repetition()?->value === Repetition::OPTIONAL->value, + 'children' => [], + ]; + + foreach ($this->children as $column) { + $ddlArray['children'][$column->name()] = $column->ddl(); + } + + return $ddlArray; + } + + public function flatPath() : string + { + return $this->root->flatPath(); + } + + /** + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress MixedReturnStatement + * @psalm-suppress MixedInferredReturnType + */ + public function getListElement() : Column + { + if ($this->isList()) { + /** @phpstan-ignore-next-line */ + return $this->children()[0]->children()[0]; + } + + throw new InvalidArgumentException('Column ' . $this->flatPath() . ' is not a list'); + } + + /** + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress MixedReturnStatement + * @psalm-suppress MixedInferredReturnType + */ + public function getMapKeyElement() : Column + { + if ($this->isMap()) { + /** @phpstan-ignore-next-line */ + return $this->children()[0]->children()[0]; + } + + throw new InvalidArgumentException('Column ' . $this->flatPath() . ' is not a map'); + } + + /** + * @psalm-suppress UndefinedInterfaceMethod + * @psalm-suppress MixedReturnStatement + * @psalm-suppress MixedInferredReturnType + */ + public function getMapValueElement() : Column + { + if ($this->isMap()) { + /** @phpstan-ignore-next-line */ + return $this->children()[0]->children()[1]; + } + + throw new InvalidArgumentException('Column ' . $this->flatPath() . ' is not a map'); + } + + public function isList() : bool + { + return $this->logicalType()?->name() === 'LIST'; + } + + public function isListElement() : bool + { + if ($this->parent !== null) { + // element + if ($this->parent->logicalType()?->name() === 'LIST') { + return true; + } + + // list.element + if ($this->parent->parent()?->logicalType()?->name() === 'LIST') { + return true; + } + } + + return false; + } + + public function isMap() : bool + { + return $this->logicalType()?->name() === 'MAP'; + } + + public function isMapElement() : bool + { + if ($this->parent === null) { + return false; + } + + if ($this->parent()?->logicalType()?->name() === 'MAP') { + return true; + } + + if ($this->parent()?->parent()?->logicalType()?->name() === 'MAP') { + return true; + } + + return false; + } + + public function isStruct() : bool + { + if ($this->isMap()) { + return false; + } + + if ($this->isList()) { + return false; + } + + return true; + } + + public function isStructElement() : bool + { + if ($this->isMapElement()) { + return false; + } + + if ($this->isListElement()) { + return false; + } + + return true; + } + + public function logicalType() : ?LogicalType + { + return $this->root->logicalType(); + } + + public function maxDefinitionsLevel() : int + { + return $this->maxDefinitionsLevel; + } + + public function maxRepetitionsLevel() : int + { + return $this->maxRepetitionsLevel; + } + + public function name() : string + { + return $this->root->name(); + } + + public function normalize() : array + { + return [ + 'type' => 'nested', + 'name' => $this->name(), + 'flat_path' => $this->flatPath(), + 'physical_type' => $this->type()->name, + 'logical_type' => $this->logicalType()?->name(), + 'repetition' => $this->repetition()?->name, + 'max_definition_level' => $this->maxDefinitionsLevel(), + 'max_repetition_level' => $this->maxRepetitionsLevel(), + 'is_map' => $this->isMap(), + 'is_list' => $this->isList(), + 'is_struct' => $this->isStruct(), + 'is_list_element' => $this->isListElement(), + 'is_map_element' => $this->isMapElement(), + 'is_struct_element' => $this->isStructElement(), + 'children' => $this->normalizeChildren(), + ]; + } + + public function normalizeChildren() : array + { + $normalized = []; + + foreach ($this->children as $child) { + $childData = [ + 'type' => $child->type()->name, + 'logical_type' => $child->logicalType()?->name(), + 'optional' => $child->repetition() === Repetition::OPTIONAL, + 'repeated' => $child->repetition() === Repetition::REPEATED, + 'is_list_element' => $child->isListElement(), + 'is_map_element' => $child->isMapElement(), + 'is_struct_element' => $child->isStructElement(), + ]; + + if ($child instanceof self) { + $childData['children'] = $child->normalizeChildren(); + } + + $normalized[$child->flatPath()] = $childData; + } + + return $normalized; + } + + public function parent() : ?Column + { + return $this->parent; + } + + public function repetition() : ?Repetition + { + return $this->root->repetition(); + } + + /** + * @param array $columns + */ + public function setChildren(array $columns) : void + { + $this->children = $columns; + } + + public function type() : PhysicalType + { + return $this->root->type(); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/PhysicalType.php b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/PhysicalType.php new file mode 100644 index 000000000..736ef43fc --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/ParquetFile/Schema/PhysicalType.php @@ -0,0 +1,15 @@ +options, $this->byteOrder, $this->logger); + } + + /** + * @param resource $stream + */ + public function readStream($stream) : ParquetFile + { + /** @psalm-suppress DocblockTypeContradiction */ + if (!\is_resource($stream)) { + throw new InvalidArgumentException('Given argument is not a valid resource'); + } + + $streamMetadata = \stream_get_meta_data($stream); + + if (!$streamMetadata['seekable']) { + throw new InvalidArgumentException('Given stream is not seekable'); + } + + return new ParquetFile($stream, $this->options, $this->byteOrder, $this->logger); + } + + public function set(Options $options) : void + { + $this->options = $options; + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Resources/Thrift/parquet.thrift b/src/lib/parquet/src/Flow/Parquet/Resources/Thrift/parquet.thrift new file mode 100644 index 000000000..a468302e3 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Resources/Thrift/parquet.thrift @@ -0,0 +1,1087 @@ +/** + * 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. + */ + +/** + * File format description for the parquet file format + */ +namespace cpp parquet +namespace java org.apache.parquet.format +namespace php Flow.Parquet.Thrift + +/** + * Types supported by Parquet. These types are intended to be used in combination + * with the encodings to control the on disk storage format. + * For example INT16 is not included as a type since a good encoding of INT32 + * would handle this. + */ +enum Type { + BOOLEAN = 0; + INT32 = 1; + INT64 = 2; + INT96 = 3; // deprecated, only used by legacy implementations. + FLOAT = 4; + DOUBLE = 5; + BYTE_ARRAY = 6; + FIXED_LEN_BYTE_ARRAY = 7; +} + +/** + * DEPRECATED: Common types used by frameworks(e.g. hive, pig) using parquet. + * ConvertedType is superseded by LogicalType. This enum should not be extended. + * + * See LogicalTypes.md for conversion between ConvertedType and LogicalType. + */ +enum ConvertedType { + /** a BYTE_ARRAY actually contains UTF8 encoded chars */ + UTF8 = 0; + + /** a map is converted as an optional field containing a repeated key/value pair */ + MAP = 1; + + /** a key/value pair is converted into a group of two fields */ + MAP_KEY_VALUE = 2; + + /** a list is converted into an optional field containing a repeated field for its + * values */ + LIST = 3; + + /** an enum is converted into a binary field */ + ENUM = 4; + + /** + * A decimal value. + * + * This may be used to annotate binary or fixed primitive types. The + * underlying byte array stores the unscaled value encoded as two's + * complement using big-endian byte order (the most significant byte is the + * zeroth element). The value of the decimal is the value * 10^{-scale}. + * + * This must be accompanied by a (maximum) precision and a scale in the + * SchemaElement. The precision specifies the number of digits in the decimal + * and the scale stores the location of the decimal point. For example 1.23 + * would have precision 3 (3 total digits) and scale 2 (the decimal point is + * 2 digits over). + */ + DECIMAL = 5; + + /** + * A Date + * + * Stored as days since Unix epoch, encoded as the INT32 physical type. + * + */ + DATE = 6; + + /** + * A time + * + * The total number of milliseconds since midnight. The value is stored + * as an INT32 physical type. + */ + TIME_MILLIS = 7; + + /** + * A time. + * + * The total number of microseconds since midnight. The value is stored as + * an INT64 physical type. + */ + TIME_MICROS = 8; + + /** + * A date/time combination + * + * Date and time recorded as milliseconds since the Unix epoch. Recorded as + * a physical type of INT64. + */ + TIMESTAMP_MILLIS = 9; + + /** + * A date/time combination + * + * Date and time recorded as microseconds since the Unix epoch. The value is + * stored as an INT64 physical type. + */ + TIMESTAMP_MICROS = 10; + + + /** + * An unsigned integer value. + * + * The number describes the maximum number of meaningful data bits in + * the stored value. 8, 16 and 32 bit values are stored using the + * INT32 physical type. 64 bit values are stored using the INT64 + * physical type. + * + */ + UINT_8 = 11; + UINT_16 = 12; + UINT_32 = 13; + UINT_64 = 14; + + /** + * A signed integer value. + * + * The number describes the maximum number of meaningful data bits in + * the stored value. 8, 16 and 32 bit values are stored using the + * INT32 physical type. 64 bit values are stored using the INT64 + * physical type. + * + */ + INT_8 = 15; + INT_16 = 16; + INT_32 = 17; + INT_64 = 18; + + /** + * An embedded JSON document + * + * A JSON document embedded within a single UTF8 column. + */ + JSON = 19; + + /** + * An embedded BSON document + * + * A BSON document embedded within a single BINARY column. + */ + BSON = 20; + + /** + * An interval of time + * + * This type annotates data stored as a FIXED_LEN_BYTE_ARRAY of length 12 + * This data is composed of three separate little endian unsigned + * integers. Each stores a component of a duration of time. The first + * integer identifies the number of months associated with the duration, + * the second identifies the number of days associated with the duration + * and the third identifies the number of milliseconds associated with + * the provided duration. This duration of time is independent of any + * particular timezone or date. + */ + INTERVAL = 21; +} + +/** + * Representation of Schemas + */ +enum FieldRepetitionType { + /** This field is required (can not be null) and each record has exactly 1 value. */ + REQUIRED = 0; + + /** The field is optional (can be null) and each record has 0 or 1 values. */ + OPTIONAL = 1; + + /** The field is repeated and can contain 0 or more values */ + REPEATED = 2; +} + +/** + * Statistics per row group and per page + * All fields are optional. + */ +struct Statistics { + /** + * DEPRECATED: min and max value of the column. Use min_value and max_value. + * + * Values are encoded using PLAIN encoding, except that variable-length byte + * arrays do not include a length prefix. + * + * These fields encode min and max values determined by signed comparison + * only. New files should use the correct order for a column's logical type + * and store the values in the min_value and max_value fields. + * + * To support older readers, these may be set when the column order is + * signed. + */ + 1: optional binary max; + 2: optional binary min; + /** count of null value in the column */ + 3: optional i64 null_count; + /** count of distinct values occurring */ + 4: optional i64 distinct_count; + /** + * Min and max values for the column, determined by its ColumnOrder. + * + * Values are encoded using PLAIN encoding, except that variable-length byte + * arrays do not include a length prefix. + */ + 5: optional binary max_value; + 6: optional binary min_value; +} + +/** Empty structs to use as logical type annotations */ +struct StringType {} // allowed for BINARY, must be encoded with UTF-8 +struct UUIDType {} // allowed for FIXED[16], must encoded raw UUID bytes +struct MapType {} // see LogicalTypes.md +struct ListType {} // see LogicalTypes.md +struct EnumType {} // allowed for BINARY, must be encoded with UTF-8 +struct DateType {} // allowed for INT32 + +/** + * Logical type to annotate a column that is always null. + * + * Sometimes when discovering the schema of existing data, values are always + * null and the physical type can't be determined. This annotation signals + * the case where the physical type was guessed from all null values. + */ +struct NullType {} // allowed for any physical type, only null values stored + +/** + * Decimal logical type annotation + * + * Scale must be zero or a positive integer less than or equal to the precision. + * Precision must be a non-zero positive integer. + * + * To maintain forward-compatibility in v1, implementations using this logical + * type must also set scale and precision on the annotated SchemaElement. + * + * Allowed for physical types: INT32, INT64, FIXED, and BINARY + */ +struct DecimalType { + 1: required i32 scale + 2: required i32 precision +} + +/** Time units for logical types */ +struct MilliSeconds {} +struct MicroSeconds {} +struct NanoSeconds {} +union TimeUnit { + 1: MilliSeconds MILLIS + 2: MicroSeconds MICROS + 3: NanoSeconds NANOS +} + +/** + * Timestamp logical type annotation + * + * Allowed for physical types: INT64 + */ +struct TimestampType { + 1: required bool isAdjustedToUTC + 2: required TimeUnit unit +} + +/** + * Time logical type annotation + * + * Allowed for physical types: INT32 (millis), INT64 (micros, nanos) + */ +struct TimeType { + 1: required bool isAdjustedToUTC + 2: required TimeUnit unit +} + +/** + * Integer logical type annotation + * + * bitWidth must be 8, 16, 32, or 64. + * + * Allowed for physical types: INT32, INT64 + */ +struct IntType { + 1: required i8 bitWidth + 2: required bool isSigned +} + +/** + * Embedded JSON logical type annotation + * + * Allowed for physical types: BINARY + */ +struct JsonType { +} + +/** + * Embedded BSON logical type annotation + * + * Allowed for physical types: BINARY + */ +struct BsonType { +} + +/** + * LogicalType annotations to replace ConvertedType. + * + * To maintain compatibility, implementations using LogicalType for a + * SchemaElement must also set the corresponding ConvertedType (if any) + * from the following table. + */ +union LogicalType { + 1: StringType STRING // use ConvertedType UTF8 + 2: MapType MAP // use ConvertedType MAP + 3: ListType LIST // use ConvertedType LIST + 4: EnumType ENUM // use ConvertedType ENUM + 5: DecimalType DECIMAL // use ConvertedType DECIMAL + SchemaElement.{scale, precision} + 6: DateType DATE // use ConvertedType DATE + + // use ConvertedType TIME_MICROS for TIME(isAdjustedToUTC = *, unit = MICROS) + // use ConvertedType TIME_MILLIS for TIME(isAdjustedToUTC = *, unit = MILLIS) + 7: TimeType TIME + + // use ConvertedType TIMESTAMP_MICROS for TIMESTAMP(isAdjustedToUTC = *, unit = MICROS) + // use ConvertedType TIMESTAMP_MILLIS for TIMESTAMP(isAdjustedToUTC = *, unit = MILLIS) + 8: TimestampType TIMESTAMP + + // 9: reserved for INTERVAL + 10: IntType INTEGER // use ConvertedType INT_* or UINT_* + 11: NullType UNKNOWN // no compatible ConvertedType + 12: JsonType JSON // use ConvertedType JSON + 13: BsonType BSON // use ConvertedType BSON + 14: UUIDType UUID // no compatible ConvertedType +} + +/** + * Represents a element inside a schema definition. + * - if it is a group (inner node) then type is undefined and num_children is defined + * - if it is a primitive type (leaf) then type is defined and num_children is undefined + * the nodes are listed in depth first traversal order. + */ +struct SchemaElement { + /** Data type for this field. Not set if the current element is a non-leaf node */ + 1: optional Type type; + + /** If type is FIXED_LEN_BYTE_ARRAY, this is the byte length of the values. + * Otherwise, if specified, this is the maximum bit length to store any of the values. + * (e.g. a low cardinality INT col could have this set to 3). Note that this is + * in the schema, and therefore fixed for the entire file. + */ + 2: optional i32 type_length; + + /** repetition of the field. The root of the schema does not have a repetition_type. + * All other nodes must have one */ + 3: optional FieldRepetitionType repetition_type; + + /** Name of the field in the schema */ + 4: required string name; + + /** Nested fields. Since thrift does not support nested fields, + * the nesting is flattened to a single list by a depth-first traversal. + * The children count is used to construct the nested relationship. + * This field is not set when the element is a primitive type + */ + 5: optional i32 num_children; + + /** + * DEPRECATED: When the schema is the result of a conversion from another model. + * Used to record the original type to help with cross conversion. + * + * This is superseded by logicalType. + */ + 6: optional ConvertedType converted_type; + + /** + * DEPRECATED: Used when this column contains decimal data. + * See the DECIMAL converted type for more details. + * + * This is superseded by using the DecimalType annotation in logicalType. + */ + 7: optional i32 scale + 8: optional i32 precision + + /** When the original schema supports field ids, this will save the + * original field id in the parquet schema + */ + 9: optional i32 field_id; + + /** + * The logical type of this SchemaElement + * + * LogicalType replaces ConvertedType, but ConvertedType is still required + * for some logical types to ensure forward-compatibility in format v1. + */ + 10: optional LogicalType logicalType +} + +/** + * Encodings supported by Parquet. Not all encodings are valid for all types. These + * enums are also used to specify the encoding of definition and repetition levels. + * See the accompanying doc for the details of the more complicated encodings. + */ +enum Encoding { + /** Default encoding. + * BOOLEAN - 1 bit per value. 0 is false; 1 is true. + * INT32 - 4 bytes per value. Stored as little-endian. + * INT64 - 8 bytes per value. Stored as little-endian. + * FLOAT - 4 bytes per value. IEEE. Stored as little-endian. + * DOUBLE - 8 bytes per value. IEEE. Stored as little-endian. + * BYTE_ARRAY - 4 byte length stored as little endian, followed by bytes. + * FIXED_LEN_BYTE_ARRAY - Just the bytes. + */ + PLAIN = 0; + + /** Group VarInt encoding for INT32/INT64. + * This encoding is deprecated. It was never used + */ + // GROUP_VAR_INT = 1; + + /** + * Deprecated: Dictionary encoding. The values in the dictionary are encoded in the + * plain type. + * in a data page use RLE_DICTIONARY instead. + * in a Dictionary page use PLAIN instead + */ + PLAIN_DICTIONARY = 2; + + /** Group packed run length encoding. Usable for definition/repetition levels + * encoding and Booleans (on one bit: 0 is false; 1 is true.) + */ + RLE = 3; + + /** Bit packed encoding. This can only be used if the data has a known max + * width. Usable for definition/repetition levels encoding. + */ + BIT_PACKED = 4; + + /** Delta encoding for integers. This can be used for int columns and works best + * on sorted data + */ + DELTA_BINARY_PACKED = 5; + + /** Encoding for byte arrays to separate the length values and the data. The lengths + * are encoded using DELTA_BINARY_PACKED + */ + DELTA_LENGTH_BYTE_ARRAY = 6; + + /** Incremental-encoded byte array. Prefix lengths are encoded using DELTA_BINARY_PACKED. + * Suffixes are stored as delta length byte arrays. + */ + DELTA_BYTE_ARRAY = 7; + + /** Dictionary encoding: the ids are encoded using the RLE encoding + */ + RLE_DICTIONARY = 8; + + /** Encoding for floating-point data. + K byte-streams are created where K is the size in bytes of the data type. + The individual bytes of an FP value are scattered to the corresponding stream and + the streams are concatenated. + This itself does not reduce the size of the data but can lead to better compression + afterwards. + */ + BYTE_STREAM_SPLIT = 9; +} + +/** + * Supported compression algorithms. + * + * Codecs added in format version X.Y can be read by readers based on X.Y and later. + * Codec support may vary between readers based on the format version and + * libraries available at runtime. + * + * See Compression.md for a detailed specification of these algorithms. + */ +enum CompressionCodec { + UNCOMPRESSED = 0; + SNAPPY = 1; + GZIP = 2; + LZO = 3; + BROTLI = 4; // Added in 2.4 + LZ4 = 5; // DEPRECATED (Added in 2.4) + ZSTD = 6; // Added in 2.4 + LZ4_RAW = 7; // Added in 2.9 +} + +enum PageType { + DATA_PAGE = 0; + INDEX_PAGE = 1; + DICTIONARY_PAGE = 2; + DATA_PAGE_V2 = 3; +} + +/** + * Enum to annotate whether lists of min/max elements inside ColumnIndex + * are ordered and if so, in which direction. + */ +enum BoundaryOrder { + UNORDERED = 0; + ASCENDING = 1; + DESCENDING = 2; +} + +/** Data page header */ +struct DataPageHeader { + /** Number of values, including NULLs, in this data page. **/ + 1: required i32 num_values + + /** Encoding used for this data page **/ + 2: required Encoding encoding + + /** Encoding used for definition levels **/ + 3: required Encoding definition_level_encoding; + + /** Encoding used for repetition levels **/ + 4: required Encoding repetition_level_encoding; + + /** Optional statistics for the data in this page**/ + 5: optional Statistics statistics; +} + +struct IndexPageHeader { + // TODO +} + +/** + * The dictionary page must be placed at the first position of the column chunk + * if it is partly or completely dictionary encoded. At most one dictionary page + * can be placed in a column chunk. + **/ +struct DictionaryPageHeader { + /** Number of values in the dictionary **/ + 1: required i32 num_values; + + /** Encoding using this dictionary page **/ + 2: required Encoding encoding + + /** If true, the entries in the dictionary are sorted in ascending order **/ + 3: optional bool is_sorted; +} + +/** + * New page format allowing reading levels without decompressing the data + * Repetition and definition levels are uncompressed + * The remaining section containing the data is compressed if is_compressed is true + **/ +struct DataPageHeaderV2 { + /** Number of values, including NULLs, in this data page. **/ + 1: required i32 num_values + /** Number of NULL values, in this data page. + Number of non-null = num_values - num_nulls which is also the number of values in the data section **/ + 2: required i32 num_nulls + /** Number of rows in this data page. which means pages change on record boundaries (r = 0) **/ + 3: required i32 num_rows + /** Encoding used for data in this page **/ + 4: required Encoding encoding + + // repetition levels and definition levels are always using RLE (without size in it) + + /** length of the definition levels */ + 5: required i32 definition_levels_byte_length; + /** length of the repetition levels */ + 6: required i32 repetition_levels_byte_length; + + /** whether the values are compressed. + Which means the section of the page between + definition_levels_byte_length + repetition_levels_byte_length + 1 and compressed_page_size (included) + is compressed with the compression_codec. + If missing it is considered compressed */ + 7: optional bool is_compressed = true; + + /** optional statistics for the data in this page **/ + 8: optional Statistics statistics; +} + +/** Block-based algorithm type annotation. **/ +struct SplitBlockAlgorithm {} +/** The algorithm used in Bloom filter. **/ +union BloomFilterAlgorithm { + /** Block-based Bloom filter. **/ + 1: SplitBlockAlgorithm BLOCK; +} + +/** Hash strategy type annotation. xxHash is an extremely fast non-cryptographic hash + * algorithm. It uses 64 bits version of xxHash. + **/ +struct XxHash {} + +/** + * The hash function used in Bloom filter. This function takes the hash of a column value + * using plain encoding. + **/ +union BloomFilterHash { + /** xxHash Strategy. **/ + 1: XxHash XXHASH; +} + +/** + * The compression used in the Bloom filter. + **/ +struct Uncompressed {} +union BloomFilterCompression { + 1: Uncompressed UNCOMPRESSED; +} + +/** + * Bloom filter header is stored at beginning of Bloom filter data of each column + * and followed by its bitset. + **/ +struct BloomFilterHeader { + /** The size of bitset in bytes **/ + 1: required i32 numBytes; + /** The algorithm for setting bits. **/ + 2: required BloomFilterAlgorithm algorithm; + /** The hash function used for Bloom filter. **/ + 3: required BloomFilterHash hash; + /** The compression used in the Bloom filter **/ + 4: required BloomFilterCompression compression; +} + +struct PageHeader { + /** the type of the page: indicates which of the *_header fields is set **/ + 1: required PageType type + + /** Uncompressed page size in bytes (not including this header) **/ + 2: required i32 uncompressed_page_size + + /** Compressed (and potentially encrypted) page size in bytes, not including this header **/ + 3: required i32 compressed_page_size + + /** The 32-bit CRC checksum for the page, to be be calculated as follows: + * + * - The standard CRC32 algorithm is used (with polynomial 0x04C11DB7, + * the same as in e.g. GZip). + * - All page types can have a CRC (v1 and v2 data pages, dictionary pages, + * etc.). + * - The CRC is computed on the serialization binary representation of the page + * (as written to disk), excluding the page header. For example, for v1 + * data pages, the CRC is computed on the concatenation of repetition levels, + * definition levels and column values (optionally compressed, optionally + * encrypted). + * - The CRC computation therefore takes place after any compression + * and encryption steps, if any. + * + * If enabled, this allows for disabling checksumming in HDFS if only a few + * pages need to be read. + */ + 4: optional i32 crc + + // Headers for page specific data. One only will be set. + 5: optional DataPageHeader data_page_header; + 6: optional IndexPageHeader index_page_header; + 7: optional DictionaryPageHeader dictionary_page_header; + 8: optional DataPageHeaderV2 data_page_header_v2; +} + +/** + * Wrapper struct to store key values + */ + struct KeyValue { + 1: required string key + 2: optional string value +} + +/** + * Wrapper struct to specify sort order + */ +struct SortingColumn { + /** The column index (in this row group) **/ + 1: required i32 column_idx + + /** If true, indicates this column is sorted in descending order. **/ + 2: required bool descending + + /** If true, nulls will come before non-null values, otherwise, + * nulls go at the end. */ + 3: required bool nulls_first +} + +/** + * statistics of a given page type and encoding + */ +struct PageEncodingStats { + + /** the page type (data/dic/...) **/ + 1: required PageType page_type; + + /** encoding of the page **/ + 2: required Encoding encoding; + + /** number of pages of this type with this encoding **/ + 3: required i32 count; + +} + +/** + * Description for column metadata + */ +struct ColumnMetaData { + /** Type of this column **/ + 1: required Type type + + /** Set of all encodings used for this column. The purpose is to validate + * whether we can decode those pages. **/ + 2: required list encodings + + /** Path in schema **/ + 3: required list path_in_schema + + /** Compression codec **/ + 4: required CompressionCodec codec + + /** Number of values in this column **/ + 5: required i64 num_values + + /** total byte size of all uncompressed pages in this column chunk (including the headers) **/ + 6: required i64 total_uncompressed_size + + /** total byte size of all compressed, and potentially encrypted, pages + * in this column chunk (including the headers) **/ + 7: required i64 total_compressed_size + + /** Optional key/value metadata **/ + 8: optional list key_value_metadata + + /** Byte offset from beginning of file to first data page **/ + 9: required i64 data_page_offset + + /** Byte offset from beginning of file to root index page **/ + 10: optional i64 index_page_offset + + /** Byte offset from the beginning of file to first (only) dictionary page **/ + 11: optional i64 dictionary_page_offset + + /** optional statistics for this column chunk */ + 12: optional Statistics statistics; + + /** Set of all encodings used for pages in this column chunk. + * This information can be used to determine if all data pages are + * dictionary encoded for example **/ + 13: optional list encoding_stats; + + /** Byte offset from beginning of file to Bloom filter data. **/ + 14: optional i64 bloom_filter_offset; + + /** Size of Bloom filter data including the serialized header, in bytes. + * Added in 2.10 so readers may not read this field from old files and + * it can be obtained after the BloomFilterHeader has been deserialized. + * Writers should write this field so readers can read the bloom filter + * in a single I/O. + */ + 15: optional i32 bloom_filter_length; +} + +struct EncryptionWithFooterKey { +} + +struct EncryptionWithColumnKey { + /** Column path in schema **/ + 1: required list path_in_schema + + /** Retrieval metadata of column encryption key **/ + 2: optional binary key_metadata +} + +union ColumnCryptoMetaData { + 1: EncryptionWithFooterKey ENCRYPTION_WITH_FOOTER_KEY + 2: EncryptionWithColumnKey ENCRYPTION_WITH_COLUMN_KEY +} + +struct ColumnChunk { + /** File where column data is stored. If not set, assumed to be same file as + * metadata. This path is relative to the current file. + **/ + 1: optional string file_path + + /** Byte offset in file_path to the ColumnMetaData **/ + 2: required i64 file_offset + + /** Column metadata for this chunk. This is the same content as what is at + * file_path/file_offset. Having it here has it replicated in the file + * metadata. + **/ + 3: optional ColumnMetaData meta_data + + /** File offset of ColumnChunk's OffsetIndex **/ + 4: optional i64 offset_index_offset + + /** Size of ColumnChunk's OffsetIndex, in bytes **/ + 5: optional i32 offset_index_length + + /** File offset of ColumnChunk's ColumnIndex **/ + 6: optional i64 column_index_offset + + /** Size of ColumnChunk's ColumnIndex, in bytes **/ + 7: optional i32 column_index_length + + /** Crypto metadata of encrypted columns **/ + 8: optional ColumnCryptoMetaData crypto_metadata + + /** Encrypted column metadata for this chunk **/ + 9: optional binary encrypted_column_metadata +} + +struct RowGroup { + /** Metadata for each column chunk in this row group. + * This list must have the same order as the SchemaElement list in FileMetaData. + **/ + 1: required list columns + + /** Total byte size of all the uncompressed column data in this row group **/ + 2: required i64 total_byte_size + + /** Number of rows in this row group **/ + 3: required i64 num_rows + + /** If set, specifies a sort ordering of the rows in this RowGroup. + * The sorting columns can be a subset of all the columns. + */ + 4: optional list sorting_columns + + /** Byte offset from beginning of file to first page (data or dictionary) + * in this row group **/ + 5: optional i64 file_offset + + /** Total byte size of all compressed (and potentially encrypted) column data + * in this row group **/ + 6: optional i64 total_compressed_size + + /** Row group ordinal in the file **/ + 7: optional i16 ordinal +} + +/** Empty struct to signal the order defined by the physical or logical type */ +struct TypeDefinedOrder {} + +/** + * Union to specify the order used for the min_value and max_value fields for a + * column. This union takes the role of an enhanced enum that allows rich + * elements (which will be needed for a collation-based ordering in the future). + * + * Possible values are: + * * TypeDefinedOrder - the column uses the order defined by its logical or + * physical type (if there is no logical type). + * + * If the reader does not support the value of this union, min and max stats + * for this column should be ignored. + */ +union ColumnOrder { + + /** + * The sort orders for logical types are: + * UTF8 - unsigned byte-wise comparison + * INT8 - signed comparison + * INT16 - signed comparison + * INT32 - signed comparison + * INT64 - signed comparison + * UINT8 - unsigned comparison + * UINT16 - unsigned comparison + * UINT32 - unsigned comparison + * UINT64 - unsigned comparison + * DECIMAL - signed comparison of the represented value + * DATE - signed comparison + * TIME_MILLIS - signed comparison + * TIME_MICROS - signed comparison + * TIMESTAMP_MILLIS - signed comparison + * TIMESTAMP_MICROS - signed comparison + * INTERVAL - unsigned comparison + * JSON - unsigned byte-wise comparison + * BSON - unsigned byte-wise comparison + * ENUM - unsigned byte-wise comparison + * LIST - undefined + * MAP - undefined + * + * In the absence of logical types, the sort order is determined by the physical type: + * BOOLEAN - false, true + * INT32 - signed comparison + * INT64 - signed comparison + * INT96 (only used for legacy timestamps) - undefined + * FLOAT - signed comparison of the represented value (*) + * DOUBLE - signed comparison of the represented value (*) + * BYTE_ARRAY - unsigned byte-wise comparison + * FIXED_LEN_BYTE_ARRAY - unsigned byte-wise comparison + * + * (*) Because the sorting order is not specified properly for floating + * point values (relations vs. total ordering) the following + * compatibility rules should be applied when reading statistics: + * - If the min is a NaN, it should be ignored. + * - If the max is a NaN, it should be ignored. + * - If the min is +0, the row group may contain -0 values as well. + * - If the max is -0, the row group may contain +0 values as well. + * - When looking for NaN values, min and max should be ignored. + * + * When writing statistics the following rules should be followed: + * - NaNs should not be written to min or max statistics fields. + * - If the computed max value is zero (whether negative or positive), + * `+0.0` should be written into the max statistics field. + * - If the computed min value is zero (whether negative or positive), + * `-0.0` should be written into the min statistics field. + */ + 1: TypeDefinedOrder TYPE_ORDER; +} + +struct PageLocation { + /** Offset of the page in the file **/ + 1: required i64 offset + + /** + * Size of the page, including header. Sum of compressed_page_size and header + * length + */ + 2: required i32 compressed_page_size + + /** + * Index within the RowGroup of the first row of the page; this means pages + * change on record boundaries (r = 0). + */ + 3: required i64 first_row_index +} + +struct OffsetIndex { + /** + * PageLocations, ordered by increasing PageLocation.offset. It is required + * that page_locations[i].first_row_index < page_locations[i+1].first_row_index. + */ + 1: required list page_locations +} + +/** + * Description for ColumnIndex. + * Each [i] refers to the page at OffsetIndex.page_locations[i] + */ +struct ColumnIndex { + /** + * A list of Boolean values to determine the validity of the corresponding + * min and max values. If true, a page contains only null values, and writers + * have to set the corresponding entries in min_values and max_values to + * byte[0], so that all lists have the same length. If false, the + * corresponding entries in min_values and max_values must be valid. + */ + 1: required list null_pages + + /** + * Two lists containing lower and upper bounds for the values of each page + * determined by the ColumnOrder of the column. These may be the actual + * minimum and maximum values found on a page, but can also be (more compact) + * values that do not exist on a page. For example, instead of storing ""Blart + * Versenwald III", a writer may set min_values[i]="B", max_values[i]="C". + * Such more compact values must still be valid values within the column's + * logical type. Readers must make sure that list entries are populated before + * using them by inspecting null_pages. + */ + 2: required list min_values + 3: required list max_values + + /** + * Stores whether both min_values and max_values are ordered and if so, in + * which direction. This allows readers to perform binary searches in both + * lists. Readers cannot assume that max_values[i] <= min_values[i+1], even + * if the lists are ordered. + */ + 4: required BoundaryOrder boundary_order + + /** A list containing the number of null values for each page **/ + 5: optional list null_counts +} + +struct AesGcmV1 { + /** AAD prefix **/ + 1: optional binary aad_prefix + + /** Unique file identifier part of AAD suffix **/ + 2: optional binary aad_file_unique + + /** In files encrypted with AAD prefix without storing it, + * readers must supply the prefix **/ + 3: optional bool supply_aad_prefix +} + +struct AesGcmCtrV1 { + /** AAD prefix **/ + 1: optional binary aad_prefix + + /** Unique file identifier part of AAD suffix **/ + 2: optional binary aad_file_unique + + /** In files encrypted with AAD prefix without storing it, + * readers must supply the prefix **/ + 3: optional bool supply_aad_prefix +} + +union EncryptionAlgorithm { + 1: AesGcmV1 AES_GCM_V1 + 2: AesGcmCtrV1 AES_GCM_CTR_V1 +} + +/** + * Description for file metadata + */ +struct FileMetaData { + /** Version of this file **/ + 1: required i32 version + + /** Parquet schema for this file. This schema contains metadata for all the columns. + * The schema is represented as a tree with a single root. The nodes of the tree + * are flattened to a list by doing a depth-first traversal. + * The column metadata contains the path in the schema for that column which can be + * used to map columns to nodes in the schema. + * The first element is the root **/ + 2: required list schema; + + /** Number of rows in this file **/ + 3: required i64 num_rows + + /** Row groups in this file **/ + 4: required list row_groups + + /** Optional key/value metadata **/ + 5: optional list key_value_metadata + + /** String for application that wrote this file. This should be in the format + * version (build ). + * e.g. impala version 1.0 (build 6cf94d29b2b7115df4de2c06e2ab4326d721eb55) + **/ + 6: optional string created_by + + /** + * Sort order used for the min_value and max_value fields in the Statistics + * objects and the min_values and max_values fields in the ColumnIndex + * objects of each column in this file. Sort orders are listed in the order + * matching the columns in the schema. The indexes are not necessary the same + * though, because only leaf nodes of the schema are represented in the list + * of sort orders. + * + * Without column_orders, the meaning of the min_value and max_value fields + * in the Statistics object and the ColumnIndex object is undefined. To ensure + * well-defined behaviour, if these fields are written to a Parquet file, + * column_orders must be written as well. + * + * The obsolete min and max fields in the Statistics object are always sorted + * by signed comparison regardless of column_orders. + */ + 7: optional list column_orders; + + /** + * Encryption algorithm. This field is set only in encrypted files + * with plaintext footer. Files with encrypted footer store algorithm id + * in FileCryptoMetaData structure. + */ + 8: optional EncryptionAlgorithm encryption_algorithm + + /** + * Retrieval metadata of key used for signing the footer. + * Used only in encrypted files with plaintext footer. + */ + 9: optional binary footer_signing_key_metadata +} + +/** Crypto metadata for files with encrypted footer **/ +struct FileCryptoMetaData { + /** + * Encryption algorithm. This field is only used for files + * with encrypted footer. Files with plaintext footer store algorithm id + * inside footer (FileMetaData structure). + */ + 1: required EncryptionAlgorithm encryption_algorithm + + /** Retrieval metadata of key used for encryption of footer, + * and (possibly) columns **/ + 2: optional binary key_metadata +} + diff --git a/src/lib/parquet/src/Flow/Parquet/Resources/Thrift/parquet_clean.thrift b/src/lib/parquet/src/Flow/Parquet/Resources/Thrift/parquet_clean.thrift new file mode 100644 index 000000000..a81d886e4 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Resources/Thrift/parquet_clean.thrift @@ -0,0 +1,354 @@ +namespace cpp parquet +namespace java org.apache.parquet.format +namespace php Flow.Parquet.Thrift + +enum Type { + BOOLEAN = 0; + INT32 = 1; + INT64 = 2; + INT96 = 3; + FLOAT = 4; + DOUBLE = 5; + BYTE_ARRAY = 6; + FIXED_LEN_BYTE_ARRAY = 7; +} + +enum ConvertedType { + UTF8 = 0; + MAP = 1; + MAP_KEY_VALUE = 2; + LIST = 3; + ENUM = 4; + DECIMAL = 5; + DATE = 6; + TIME_MILLIS = 7; + TIME_MICROS = 8; + TIMESTAMP_MILLIS = 9; + TIMESTAMP_MICROS = 10; + UINT_8 = 11; + UINT_16 = 12; + UINT_32 = 13; + UINT_64 = 14; + INT_8 = 15; + INT_16 = 16; + INT_32 = 17; + INT_64 = 18; + JSON = 19; + BSON = 20; + INTERVAL = 21; +} + +enum FieldRepetitionType { + REQUIRED = 0; + OPTIONAL = 1; + REPEATED = 2; +} + +struct Statistics { + 1: optional binary max; + 2: optional binary min; + 3: optional i64 null_count; + 4: optional i64 distinct_count; + 5: optional binary max_value; + 6: optional binary min_value; +} + +struct StringType {} +struct UUIDType {} +struct MapType {} +struct ListType {} +struct EnumType {} +struct DateType {} + +struct NullType {} + +struct DecimalType { + 1: required i32 scale + 2: required i32 precision +} + +struct MilliSeconds {} +struct MicroSeconds {} +struct NanoSeconds {} +union TimeUnit { + 1: MilliSeconds MILLIS + 2: MicroSeconds MICROS + 3: NanoSeconds NANOS +} + +struct TimestampType { + 1: required bool isAdjustedToUTC + 2: required TimeUnit unit +} + +struct TimeType { + 1: required bool isAdjustedToUTC + 2: required TimeUnit unit +} + +struct IntType { + 1: required i8 bitWidth + 2: required bool isSigned +} + +struct JsonType { +} + +struct BsonType { +} + +union LogicalType { + 1: StringType STRING + 2: MapType MAP + 3: ListType LIST + 4: EnumType ENUM + 5: DecimalType DECIMAL + 6: DateType DATE + 7: TimeType TIME + 8: TimestampType TIMESTAMP + 10: IntType INTEGER + 11: NullType UNKNOWN + 12: JsonType JSON + 13: BsonType BSON + 14: UUIDType UUID +} + +struct SchemaElement { + 1: optional Type type; + 2: optional i32 type_length; + 3: optional FieldRepetitionType repetition_type; + 4: required string name; + 5: optional i32 num_children; + 6: optional ConvertedType converted_type; + 7: optional i32 scale + 8: optional i32 precision + 9: optional i32 field_id; + 10: optional LogicalType logicalType +} + +enum Encoding { + PLAIN = 0; + PLAIN_DICTIONARY = 2; + RLE = 3; + BIT_PACKED = 4; + DELTA_BINARY_PACKED = 5; + DELTA_LENGTH_BYTE_ARRAY = 6; + DELTA_BYTE_ARRAY = 7; + RLE_DICTIONARY = 8; + BYTE_STREAM_SPLIT = 9; +} + +enum CompressionCodec { + UNCOMPRESSED = 0; + SNAPPY = 1; + GZIP = 2; + LZO = 3; + BROTLI = 4; + LZ4 = 5; + ZSTD = 6; + LZ4_RAW = 7; +} + +enum PageType { + DATA_PAGE = 0; + INDEX_PAGE = 1; + DICTIONARY_PAGE = 2; + DATA_PAGE_V2 = 3; +} + +enum BoundaryOrder { + UNORDERED = 0; + ASCENDING = 1; + DESCENDING = 2; +} + +struct DataPageHeader { + 1: required i32 num_values + 2: required Encoding encoding + 3: required Encoding definition_level_encoding; + 4: required Encoding repetition_level_encoding; + 5: optional Statistics statistics; +} + +struct IndexPageHeader { +} + +struct DictionaryPageHeader { + 1: required i32 num_values; + 2: required Encoding encoding + 3: optional bool is_sorted; +} + +struct DataPageHeaderV2 { + 1: required i32 num_values + 2: required i32 num_nulls + 3: required i32 num_rows + 4: required Encoding encoding + 5: required i32 definition_levels_byte_length; + 6: required i32 repetition_levels_byte_length; + 7: optional bool is_compressed = true; + 8: optional Statistics statistics; +} + +struct SplitBlockAlgorithm {} + +union BloomFilterAlgorithm { + 1: SplitBlockAlgorithm BLOCK; +} + +struct XxHash {} + +union BloomFilterHash { + 1: XxHash XXHASH; +} + +struct Uncompressed {} +union BloomFilterCompression { + 1: Uncompressed UNCOMPRESSED; +} + +struct BloomFilterHeader { + 1: required i32 numBytes; + 2: required BloomFilterAlgorithm algorithm; + 3: required BloomFilterHash hash; + 4: required BloomFilterCompression compression; +} + +struct PageHeader { + 1: required PageType type + 2: required i32 uncompressed_page_size + 3: required i32 compressed_page_size + 4: optional i32 crc + 5: optional DataPageHeader data_page_header; + 6: optional IndexPageHeader index_page_header; + 7: optional DictionaryPageHeader dictionary_page_header; + 8: optional DataPageHeaderV2 data_page_header_v2; +} + + struct KeyValue { + 1: required string key + 2: optional string value +} + +struct SortingColumn { + 1: required i32 column_idx + 2: required bool descending + 3: required bool nulls_first +} + +struct PageEncodingStats { + 1: required PageType page_type; + 2: required Encoding encoding; + 3: required i32 count; +} + +struct ColumnMetaData { + 1: required Type type + 2: required list encodings + 3: required list path_in_schema + 4: required CompressionCodec codec + 5: required i64 num_values + 6: required i64 total_uncompressed_size + 7: required i64 total_compressed_size + 8: optional list key_value_metadata + 9: required i64 data_page_offset + 10: optional i64 index_page_offset + 11: optional i64 dictionary_page_offset + 12: optional Statistics statistics; + 13: optional list encoding_stats; + 14: optional i64 bloom_filter_offset; + 15: optional i32 bloom_filter_length; +} + +struct EncryptionWithFooterKey { +} + +struct EncryptionWithColumnKey { + 1: required list path_in_schema + 2: optional binary key_metadata +} + +union ColumnCryptoMetaData { + 1: EncryptionWithFooterKey ENCRYPTION_WITH_FOOTER_KEY + 2: EncryptionWithColumnKey ENCRYPTION_WITH_COLUMN_KEY +} + +struct ColumnChunk { + 1: optional string file_path + 2: required i64 file_offset + 3: optional ColumnMetaData meta_data + 4: optional i64 offset_index_offset + 5: optional i32 offset_index_length + 6: optional i64 column_index_offset + 7: optional i32 column_index_length + 8: optional ColumnCryptoMetaData crypto_metadata + 9: optional binary encrypted_column_metadata +} + +struct RowGroup { + 1: required list columns + 2: required i64 total_byte_size + 3: required i64 num_rows + 4: optional list sorting_columns + 5: optional i64 file_offset + 6: optional i64 total_compressed_size + 7: optional i16 ordinal +} + +struct TypeDefinedOrder {} + +union ColumnOrder { + 1: TypeDefinedOrder TYPE_ORDER; +} + +struct PageLocation { + 1: required i64 offset + 2: required i32 compressed_page_size + 3: required i64 first_row_index +} + +struct OffsetIndex { + 1: required list page_locations +} + +struct ColumnIndex { + 1: required list null_pages + 2: required list min_values + 3: required list max_values + 4: required BoundaryOrder boundary_order + 5: optional list null_counts +} + +struct AesGcmV1 { + 1: optional binary aad_prefix + 2: optional binary aad_file_unique + 3: optional bool supply_aad_prefix +} + +struct AesGcmCtrV1 { + 1: optional binary aad_prefix + 2: optional binary aad_file_unique + 3: optional bool supply_aad_prefix +} + +union EncryptionAlgorithm { + 1: AesGcmV1 AES_GCM_V1 + 2: AesGcmCtrV1 AES_GCM_CTR_V1 +} + +struct FileMetaData { + 1: required i32 version + 2: required list schema; + 3: required i64 num_rows + 4: required list row_groups + 5: optional list key_value_metadata + 6: optional string created_by + 7: optional list column_orders; + 8: optional EncryptionAlgorithm encryption_algorithm + 9: optional binary footer_signing_key_metadata +} + +struct FileCryptoMetaData { + 1: required EncryptionAlgorithm encryption_algorithm + 2: optional binary key_metadata +} \ No newline at end of file diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/AesGcmCtrV1.php b/src/lib/parquet/src/Flow/Parquet/Thrift/AesGcmCtrV1.php new file mode 100644 index 000000000..252b3e57b --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/AesGcmCtrV1.php @@ -0,0 +1,79 @@ + [ + 'var' => 'aad_prefix', + 'isRequired' => false, + 'type' => TType::STRING, + ], + 2 => [ + 'var' => 'aad_file_unique', + 'isRequired' => false, + 'type' => TType::STRING, + ], + 3 => [ + 'var' => 'supply_aad_prefix', + 'isRequired' => false, + 'type' => TType::BOOL, + ], + ]; + + public static $isValidate = false; + + /** + * Unique file identifier part of AAD suffix *. + * + * @var string + */ + public $aad_file_unique; + + /** + * AAD prefix *. + * + * @var string + */ + public $aad_prefix; + + /** + * In files encrypted with AAD prefix without storing it, + * readers must supply the prefix *. + * + * @var bool + */ + public $supply_aad_prefix; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'AesGcmCtrV1'; + } + + public function read($input) + { + return $this->_read('AesGcmCtrV1', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('AesGcmCtrV1', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/AesGcmV1.php b/src/lib/parquet/src/Flow/Parquet/Thrift/AesGcmV1.php new file mode 100644 index 000000000..5b60f6677 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/AesGcmV1.php @@ -0,0 +1,79 @@ + [ + 'var' => 'aad_prefix', + 'isRequired' => false, + 'type' => TType::STRING, + ], + 2 => [ + 'var' => 'aad_file_unique', + 'isRequired' => false, + 'type' => TType::STRING, + ], + 3 => [ + 'var' => 'supply_aad_prefix', + 'isRequired' => false, + 'type' => TType::BOOL, + ], + ]; + + public static $isValidate = false; + + /** + * Unique file identifier part of AAD suffix *. + * + * @var string + */ + public $aad_file_unique; + + /** + * AAD prefix *. + * + * @var string + */ + public $aad_prefix; + + /** + * In files encrypted with AAD prefix without storing it, + * readers must supply the prefix *. + * + * @var bool + */ + public $supply_aad_prefix; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'AesGcmV1'; + } + + public function read($input) + { + return $this->_read('AesGcmV1', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('AesGcmV1', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterAlgorithm.php b/src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterAlgorithm.php new file mode 100644 index 000000000..66966e1c7 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterAlgorithm.php @@ -0,0 +1,58 @@ + [ + 'var' => 'BLOCK', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\SplitBlockAlgorithm', + ], + ]; + + public static $isValidate = false; + + /** + * Block-based Bloom filter. *. + * + * @var \Flow\Parquet\Thrift\SplitBlockAlgorithm + */ + public $BLOCK; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'BloomFilterAlgorithm'; + } + + public function read($input) + { + return $this->_read('BloomFilterAlgorithm', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('BloomFilterAlgorithm', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterCompression.php b/src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterCompression.php new file mode 100644 index 000000000..f6ed2aeb0 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterCompression.php @@ -0,0 +1,53 @@ + [ + 'var' => 'UNCOMPRESSED', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\Uncompressed', + ], + ]; + + public static $isValidate = false; + + /** + * @var \Flow\Parquet\Thrift\Uncompressed + */ + public $UNCOMPRESSED; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'BloomFilterCompression'; + } + + public function read($input) + { + return $this->_read('BloomFilterCompression', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('BloomFilterCompression', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterHash.php b/src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterHash.php new file mode 100644 index 000000000..088a46ed7 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterHash.php @@ -0,0 +1,59 @@ + [ + 'var' => 'XXHASH', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\XxHash', + ], + ]; + + public static $isValidate = false; + + /** + * xxHash Strategy. *. + * + * @var \Flow\Parquet\Thrift\XxHash + */ + public $XXHASH; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'BloomFilterHash'; + } + + public function read($input) + { + return $this->_read('BloomFilterHash', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('BloomFilterHash', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterHeader.php b/src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterHeader.php new file mode 100644 index 000000000..95389c861 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/BloomFilterHeader.php @@ -0,0 +1,97 @@ + [ + 'var' => 'numBytes', + 'isRequired' => true, + 'type' => TType::I32, + ], + 2 => [ + 'var' => 'algorithm', + 'isRequired' => true, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\BloomFilterAlgorithm', + ], + 3 => [ + 'var' => 'hash', + 'isRequired' => true, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\BloomFilterHash', + ], + 4 => [ + 'var' => 'compression', + 'isRequired' => true, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\BloomFilterCompression', + ], + ]; + + public static $isValidate = false; + + /** + * The algorithm for setting bits. *. + * + * @var \Flow\Parquet\Thrift\BloomFilterAlgorithm + */ + public $algorithm; + + /** + * The compression used in the Bloom filter *. + * + * @var \Flow\Parquet\Thrift\BloomFilterCompression + */ + public $compression; + + /** + * The hash function used for Bloom filter. *. + * + * @var \Flow\Parquet\Thrift\BloomFilterHash + */ + public $hash; + + /** + * The size of bitset in bytes *. + * + * @var int + */ + public $numBytes; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'BloomFilterHeader'; + } + + public function read($input) + { + return $this->_read('BloomFilterHeader', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('BloomFilterHeader', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/BoundaryOrder.php b/src/lib/parquet/src/Flow/Parquet/Thrift/BoundaryOrder.php new file mode 100644 index 000000000..40b006ea8 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/BoundaryOrder.php @@ -0,0 +1,29 @@ + 'UNORDERED', + 1 => 'ASCENDING', + 2 => 'DESCENDING', + ]; +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/BsonType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/BsonType.php new file mode 100644 index 000000000..aabc6784e --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/BsonType.php @@ -0,0 +1,43 @@ +_read('BsonType', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('BsonType', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnChunk.php b/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnChunk.php new file mode 100644 index 000000000..e20201df1 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnChunk.php @@ -0,0 +1,155 @@ + [ + 'var' => 'file_path', + 'isRequired' => false, + 'type' => TType::STRING, + ], + 2 => [ + 'var' => 'file_offset', + 'isRequired' => true, + 'type' => TType::I64, + ], + 3 => [ + 'var' => 'meta_data', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\ColumnMetaData', + ], + 4 => [ + 'var' => 'offset_index_offset', + 'isRequired' => false, + 'type' => TType::I64, + ], + 5 => [ + 'var' => 'offset_index_length', + 'isRequired' => false, + 'type' => TType::I32, + ], + 6 => [ + 'var' => 'column_index_offset', + 'isRequired' => false, + 'type' => TType::I64, + ], + 7 => [ + 'var' => 'column_index_length', + 'isRequired' => false, + 'type' => TType::I32, + ], + 8 => [ + 'var' => 'crypto_metadata', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\ColumnCryptoMetaData', + ], + 9 => [ + 'var' => 'encrypted_column_metadata', + 'isRequired' => false, + 'type' => TType::STRING, + ], + ]; + + public static $isValidate = false; + + /** + * Size of ColumnChunk's ColumnIndex, in bytes *. + * + * @var int + */ + public $column_index_length; + + /** + * File offset of ColumnChunk's ColumnIndex *. + * + * @var int + */ + public $column_index_offset; + + /** + * Crypto metadata of encrypted columns *. + * + * @var \Flow\Parquet\Thrift\ColumnCryptoMetaData + */ + public $crypto_metadata; + + /** + * Encrypted column metadata for this chunk *. + * + * @var string + */ + public $encrypted_column_metadata; + + /** + * Byte offset in file_path to the ColumnMetaData *. + * + * @var int + */ + public $file_offset; + + /** + * File where column data is stored. If not set, assumed to be same file as + * metadata. This path is relative to the current file. + * + * @var string + */ + public $file_path; + + /** + * Column metadata for this chunk. This is the same content as what is at + * file_path/file_offset. Having it here has it replicated in the file + * metadata. + * + * @var \Flow\Parquet\Thrift\ColumnMetaData + */ + public $meta_data; + + /** + * Size of ColumnChunk's OffsetIndex, in bytes *. + * + * @var int + */ + public $offset_index_length; + + /** + * File offset of ColumnChunk's OffsetIndex *. + * + * @var int + */ + public $offset_index_offset; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'ColumnChunk'; + } + + public function read($input) + { + return $this->_read('ColumnChunk', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('ColumnChunk', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnCryptoMetaData.php b/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnCryptoMetaData.php new file mode 100644 index 000000000..4f1e65c2e --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnCryptoMetaData.php @@ -0,0 +1,64 @@ + [ + 'var' => 'ENCRYPTION_WITH_FOOTER_KEY', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\EncryptionWithFooterKey', + ], + 2 => [ + 'var' => 'ENCRYPTION_WITH_COLUMN_KEY', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\EncryptionWithColumnKey', + ], + ]; + + public static $isValidate = false; + + /** + * @var \Flow\Parquet\Thrift\EncryptionWithColumnKey + */ + public $ENCRYPTION_WITH_COLUMN_KEY; + + /** + * @var \Flow\Parquet\Thrift\EncryptionWithFooterKey + */ + public $ENCRYPTION_WITH_FOOTER_KEY; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'ColumnCryptoMetaData'; + } + + public function read($input) + { + return $this->_read('ColumnCryptoMetaData', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('ColumnCryptoMetaData', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnIndex.php b/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnIndex.php new file mode 100644 index 000000000..e5dffdd2d --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnIndex.php @@ -0,0 +1,135 @@ +[i] refers to the page at OffsetIndex.page_locations[i]. + */ +class ColumnIndex extends TBase +{ + public static $_TSPEC = [ + 1 => [ + 'var' => 'null_pages', + 'isRequired' => true, + 'type' => TType::LST, + 'etype' => TType::BOOL, + 'elem' => [ + 'type' => TType::BOOL, + ], + ], + 2 => [ + 'var' => 'min_values', + 'isRequired' => true, + 'type' => TType::LST, + 'etype' => TType::STRING, + 'elem' => [ + 'type' => TType::STRING, + ], + ], + 3 => [ + 'var' => 'max_values', + 'isRequired' => true, + 'type' => TType::LST, + 'etype' => TType::STRING, + 'elem' => [ + 'type' => TType::STRING, + ], + ], + 4 => [ + 'var' => 'boundary_order', + 'isRequired' => true, + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\BoundaryOrder', + ], + 5 => [ + 'var' => 'null_counts', + 'isRequired' => false, + 'type' => TType::LST, + 'etype' => TType::I64, + 'elem' => [ + 'type' => TType::I64, + ], + ], + ]; + + public static $isValidate = false; + + /** + * Stores whether both min_values and max_values are ordered and if so, in + * which direction. This allows readers to perform binary searches in both + * lists. Readers cannot assume that max_values[i] <= min_values[i+1], even + * if the lists are ordered. + * + * @var int + */ + public $boundary_order; + + /** + * @var string[] + */ + public $max_values; + + /** + * Two lists containing lower and upper bounds for the values of each page + * determined by the ColumnOrder of the column. These may be the actual + * minimum and maximum values found on a page, but can also be (more compact) + * values that do not exist on a page. For example, instead of storing ""Blart + * Versenwald III", a writer may set min_values[i]="B", max_values[i]="C". + * Such more compact values must still be valid values within the column's + * logical type. Readers must make sure that list entries are populated before + * using them by inspecting null_pages. + * + * @var string[] + */ + public $min_values; + + /** + * A list containing the number of null values for each page *. + * + * @var int[] + */ + public $null_counts; + + /** + * A list of Boolean values to determine the validity of the corresponding + * min and max values. If true, a page contains only null values, and writers + * have to set the corresponding entries in min_values and max_values to + * byte[0], so that all lists have the same length. If false, the + * corresponding entries in min_values and max_values must be valid. + * + * @var bool[] + */ + public $null_pages; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'ColumnIndex'; + } + + public function read($input) + { + return $this->_read('ColumnIndex', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('ColumnIndex', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnMetaData.php b/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnMetaData.php new file mode 100644 index 000000000..4403dc274 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnMetaData.php @@ -0,0 +1,255 @@ + [ + 'var' => 'type', + 'isRequired' => true, + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\Type', + ], + 2 => [ + 'var' => 'encodings', + 'isRequired' => true, + 'type' => TType::LST, + 'etype' => TType::I32, + 'elem' => [ + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\Encoding', + ], + ], + 3 => [ + 'var' => 'path_in_schema', + 'isRequired' => true, + 'type' => TType::LST, + 'etype' => TType::STRING, + 'elem' => [ + 'type' => TType::STRING, + ], + ], + 4 => [ + 'var' => 'codec', + 'isRequired' => true, + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\CompressionCodec', + ], + 5 => [ + 'var' => 'num_values', + 'isRequired' => true, + 'type' => TType::I64, + ], + 6 => [ + 'var' => 'total_uncompressed_size', + 'isRequired' => true, + 'type' => TType::I64, + ], + 7 => [ + 'var' => 'total_compressed_size', + 'isRequired' => true, + 'type' => TType::I64, + ], + 8 => [ + 'var' => 'key_value_metadata', + 'isRequired' => false, + 'type' => TType::LST, + 'etype' => TType::STRUCT, + 'elem' => [ + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\KeyValue', + ], + ], + 9 => [ + 'var' => 'data_page_offset', + 'isRequired' => true, + 'type' => TType::I64, + ], + 10 => [ + 'var' => 'index_page_offset', + 'isRequired' => false, + 'type' => TType::I64, + ], + 11 => [ + 'var' => 'dictionary_page_offset', + 'isRequired' => false, + 'type' => TType::I64, + ], + 12 => [ + 'var' => 'statistics', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\Statistics', + ], + 13 => [ + 'var' => 'encoding_stats', + 'isRequired' => false, + 'type' => TType::LST, + 'etype' => TType::STRUCT, + 'elem' => [ + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\PageEncodingStats', + ], + ], + 14 => [ + 'var' => 'bloom_filter_offset', + 'isRequired' => false, + 'type' => TType::I64, + ], + 15 => [ + 'var' => 'bloom_filter_length', + 'isRequired' => false, + 'type' => TType::I32, + ], + ]; + + public static $isValidate = false; + + /** + * Size of Bloom filter data including the serialized header, in bytes. + * Added in 2.10 so readers may not read this field from old files and + * it can be obtained after the BloomFilterHeader has been deserialized. + * Writers should write this field so readers can read the bloom filter + * in a single I/O. + * + * @var int + */ + public $bloom_filter_length; + + /** + * Byte offset from beginning of file to Bloom filter data. *. + * + * @var int + */ + public $bloom_filter_offset; + + /** + * Compression codec *. + * + * @var int + */ + public $codec; + + /** + * Byte offset from beginning of file to first data page *. + * + * @var int + */ + public $data_page_offset; + + /** + * Byte offset from the beginning of file to first (only) dictionary page *. + * + * @var int + */ + public $dictionary_page_offset; + + /** + * Set of all encodings used for pages in this column chunk. + * This information can be used to determine if all data pages are + * dictionary encoded for example *. + * + * @var \Flow\Parquet\Thrift\PageEncodingStats[] + */ + public $encoding_stats; + + /** + * Set of all encodings used for this column. The purpose is to validate + * whether we can decode those pages. *. + * + * @var int[] + */ + public $encodings; + + /** + * Byte offset from beginning of file to root index page *. + * + * @var int + */ + public $index_page_offset; + + /** + * Optional key/value metadata *. + * + * @var \Flow\Parquet\Thrift\KeyValue[] + */ + public $key_value_metadata; + + /** + * Number of values in this column *. + * + * @var int + */ + public $num_values; + + /** + * Path in schema *. + * + * @var string[] + */ + public $path_in_schema; + + /** + * optional statistics for this column chunk. + * + * @var \Flow\Parquet\Thrift\Statistics + */ + public $statistics; + + /** + * total byte size of all compressed, and potentially encrypted, pages + * in this column chunk (including the headers) *. + * + * @var int + */ + public $total_compressed_size; + + /** + * total byte size of all uncompressed pages in this column chunk (including the headers) *. + * + * @var int + */ + public $total_uncompressed_size; + + /** + * Type of this column *. + * + * @var int + */ + public $type; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'ColumnMetaData'; + } + + public function read($input) + { + return $this->_read('ColumnMetaData', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('ColumnMetaData', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnOrder.php b/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnOrder.php new file mode 100644 index 000000000..69807686a --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/ColumnOrder.php @@ -0,0 +1,114 @@ + [ + 'var' => 'TYPE_ORDER', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\TypeDefinedOrder', + ], + ]; + + public static $isValidate = false; + + /** + * The sort orders for logical types are: + * UTF8 - unsigned byte-wise comparison + * INT8 - signed comparison + * INT16 - signed comparison + * INT32 - signed comparison + * INT64 - signed comparison + * UINT8 - unsigned comparison + * UINT16 - unsigned comparison + * UINT32 - unsigned comparison + * UINT64 - unsigned comparison + * DECIMAL - signed comparison of the represented value + * DATE - signed comparison + * TIME_MILLIS - signed comparison + * TIME_MICROS - signed comparison + * TIMESTAMP_MILLIS - signed comparison + * TIMESTAMP_MICROS - signed comparison + * INTERVAL - unsigned comparison + * JSON - unsigned byte-wise comparison + * BSON - unsigned byte-wise comparison + * ENUM - unsigned byte-wise comparison + * LIST - undefined + * MAP - undefined. + * + * In the absence of logical types, the sort order is determined by the physical type: + * BOOLEAN - false, true + * INT32 - signed comparison + * INT64 - signed comparison + * INT96 (only used for legacy timestamps) - undefined + * FLOAT - signed comparison of the represented value (*) + * DOUBLE - signed comparison of the represented value (*) + * BYTE_ARRAY - unsigned byte-wise comparison + * FIXED_LEN_BYTE_ARRAY - unsigned byte-wise comparison + * + * (*) Because the sorting order is not specified properly for floating + * point values (relations vs. total ordering) the following + * compatibility rules should be applied when reading statistics: + * - If the min is a NaN, it should be ignored. + * - If the max is a NaN, it should be ignored. + * - If the min is +0, the row group may contain -0 values as well. + * - If the max is -0, the row group may contain +0 values as well. + * - When looking for NaN values, min and max should be ignored. + * + * When writing statistics the following rules should be followed: + * - NaNs should not be written to min or max statistics fields. + * - If the computed max value is zero (whether negative or positive), + * `+0.0` should be written into the max statistics field. + * - If the computed min value is zero (whether negative or positive), + * `-0.0` should be written into the min statistics field. + * + * @var \Flow\Parquet\Thrift\TypeDefinedOrder + */ + public $TYPE_ORDER; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'ColumnOrder'; + } + + public function read($input) + { + return $this->_read('ColumnOrder', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('ColumnOrder', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/CompressionCodec.php b/src/lib/parquet/src/Flow/Parquet/Thrift/CompressionCodec.php new file mode 100644 index 000000000..7ba067eb4 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/CompressionCodec.php @@ -0,0 +1,49 @@ + 'UNCOMPRESSED', + 1 => 'SNAPPY', + 2 => 'GZIP', + 3 => 'LZO', + 4 => 'BROTLI', + 5 => 'LZ4', + 6 => 'ZSTD', + 7 => 'LZ4_RAW', + ]; +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/ConvertedType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/ConvertedType.php new file mode 100644 index 000000000..3d55e4c51 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/ConvertedType.php @@ -0,0 +1,185 @@ + 'UTF8', + 1 => 'MAP', + 2 => 'MAP_KEY_VALUE', + 3 => 'LIST', + 4 => 'ENUM', + 5 => 'DECIMAL', + 6 => 'DATE', + 7 => 'TIME_MILLIS', + 8 => 'TIME_MICROS', + 9 => 'TIMESTAMP_MILLIS', + 10 => 'TIMESTAMP_MICROS', + 11 => 'UINT_8', + 12 => 'UINT_16', + 13 => 'UINT_32', + 14 => 'UINT_64', + 15 => 'INT_8', + 16 => 'INT_16', + 17 => 'INT_32', + 18 => 'INT_64', + 19 => 'JSON', + 20 => 'BSON', + 21 => 'INTERVAL', + ]; +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/DataPageHeader.php b/src/lib/parquet/src/Flow/Parquet/Thrift/DataPageHeader.php new file mode 100644 index 000000000..fcfbd428f --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/DataPageHeader.php @@ -0,0 +1,109 @@ + [ + 'var' => 'num_values', + 'isRequired' => true, + 'type' => TType::I32, + ], + 2 => [ + 'var' => 'encoding', + 'isRequired' => true, + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\Encoding', + ], + 3 => [ + 'var' => 'definition_level_encoding', + 'isRequired' => true, + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\Encoding', + ], + 4 => [ + 'var' => 'repetition_level_encoding', + 'isRequired' => true, + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\Encoding', + ], + 5 => [ + 'var' => 'statistics', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\Statistics', + ], + ]; + + public static $isValidate = false; + + /** + * Encoding used for definition levels *. + * + * @var int + */ + public $definition_level_encoding; + + /** + * Encoding used for this data page *. + * + * @var int + */ + public $encoding; + + /** + * Number of values, including NULLs, in this data page. *. + * + * @var int + */ + public $num_values; + + /** + * Encoding used for repetition levels *. + * + * @var int + */ + public $repetition_level_encoding; + + /** + * Optional statistics for the data in this page*. + * + * @var \Flow\Parquet\Thrift\Statistics + */ + public $statistics; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'DataPageHeader'; + } + + public function read($input) + { + return $this->_read('DataPageHeader', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('DataPageHeader', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/DataPageHeaderV2.php b/src/lib/parquet/src/Flow/Parquet/Thrift/DataPageHeaderV2.php new file mode 100644 index 000000000..1fe2e1722 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/DataPageHeaderV2.php @@ -0,0 +1,150 @@ + [ + 'var' => 'num_values', + 'isRequired' => true, + 'type' => TType::I32, + ], + 2 => [ + 'var' => 'num_nulls', + 'isRequired' => true, + 'type' => TType::I32, + ], + 3 => [ + 'var' => 'num_rows', + 'isRequired' => true, + 'type' => TType::I32, + ], + 4 => [ + 'var' => 'encoding', + 'isRequired' => true, + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\Encoding', + ], + 5 => [ + 'var' => 'definition_levels_byte_length', + 'isRequired' => true, + 'type' => TType::I32, + ], + 6 => [ + 'var' => 'repetition_levels_byte_length', + 'isRequired' => true, + 'type' => TType::I32, + ], + 7 => [ + 'var' => 'is_compressed', + 'isRequired' => false, + 'type' => TType::BOOL, + ], + 8 => [ + 'var' => 'statistics', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\Statistics', + ], + ]; + + public static $isValidate = false; + + /** + * length of the definition levels. + * + * @var int + */ + public $definition_levels_byte_length; + + /** + * Encoding used for data in this page *. + * + * @var int + */ + public $encoding; + + /** + * whether the values are compressed. + * Which means the section of the page between + * definition_levels_byte_length + repetition_levels_byte_length + 1 and compressed_page_size (included) + * is compressed with the compression_codec. + * If missing it is considered compressed. + * + * @var bool + */ + public $is_compressed = true; + + /** + * Number of NULL values, in this data page. + * Number of non-null = num_values - num_nulls which is also the number of values in the data section *. + * + * @var int + */ + public $num_nulls; + + /** + * Number of rows in this data page. which means pages change on record boundaries (r = 0) *. + * + * @var int + */ + public $num_rows; + + /** + * Number of values, including NULLs, in this data page. *. + * + * @var int + */ + public $num_values; + + /** + * length of the repetition levels. + * + * @var int + */ + public $repetition_levels_byte_length; + + /** + * optional statistics for the data in this page *. + * + * @var \Flow\Parquet\Thrift\Statistics + */ + public $statistics; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'DataPageHeaderV2'; + } + + public function read($input) + { + return $this->_read('DataPageHeaderV2', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('DataPageHeaderV2', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/DateType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/DateType.php new file mode 100644 index 000000000..268fa7a51 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/DateType.php @@ -0,0 +1,38 @@ +_read('DateType', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('DateType', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/DecimalType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/DecimalType.php new file mode 100644 index 000000000..98a256dca --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/DecimalType.php @@ -0,0 +1,73 @@ + [ + 'var' => 'scale', + 'isRequired' => true, + 'type' => TType::I32, + ], + 2 => [ + 'var' => 'precision', + 'isRequired' => true, + 'type' => TType::I32, + ], + ]; + + public static $isValidate = false; + + /** + * @var int + */ + public $precision; + + /** + * @var int + */ + public $scale; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'DecimalType'; + } + + public function read($input) + { + return $this->_read('DecimalType', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('DecimalType', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/DictionaryPageHeader.php b/src/lib/parquet/src/Flow/Parquet/Thrift/DictionaryPageHeader.php new file mode 100644 index 000000000..c8f61e953 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/DictionaryPageHeader.php @@ -0,0 +1,84 @@ + [ + 'var' => 'num_values', + 'isRequired' => true, + 'type' => TType::I32, + ], + 2 => [ + 'var' => 'encoding', + 'isRequired' => true, + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\Encoding', + ], + 3 => [ + 'var' => 'is_sorted', + 'isRequired' => false, + 'type' => TType::BOOL, + ], + ]; + + public static $isValidate = false; + + /** + * Encoding using this dictionary page *. + * + * @var int + */ + public $encoding; + + /** + * If true, the entries in the dictionary are sorted in ascending order *. + * + * @var bool + */ + public $is_sorted; + + /** + * Number of values in the dictionary *. + * + * @var int + */ + public $num_values; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'DictionaryPageHeader'; + } + + public function read($input) + { + return $this->_read('DictionaryPageHeader', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('DictionaryPageHeader', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/Encoding.php b/src/lib/parquet/src/Flow/Parquet/Thrift/Encoding.php new file mode 100644 index 000000000..83207c768 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/Encoding.php @@ -0,0 +1,95 @@ + 'PLAIN', + 2 => 'PLAIN_DICTIONARY', + 3 => 'RLE', + 4 => 'BIT_PACKED', + 5 => 'DELTA_BINARY_PACKED', + 6 => 'DELTA_LENGTH_BYTE_ARRAY', + 7 => 'DELTA_BYTE_ARRAY', + 8 => 'RLE_DICTIONARY', + 9 => 'BYTE_STREAM_SPLIT', + ]; +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/EncryptionAlgorithm.php b/src/lib/parquet/src/Flow/Parquet/Thrift/EncryptionAlgorithm.php new file mode 100644 index 000000000..5472a2737 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/EncryptionAlgorithm.php @@ -0,0 +1,64 @@ + [ + 'var' => 'AES_GCM_V1', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\AesGcmV1', + ], + 2 => [ + 'var' => 'AES_GCM_CTR_V1', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\AesGcmCtrV1', + ], + ]; + + public static $isValidate = false; + + /** + * @var \Flow\Parquet\Thrift\AesGcmCtrV1 + */ + public $AES_GCM_CTR_V1; + + /** + * @var \Flow\Parquet\Thrift\AesGcmV1 + */ + public $AES_GCM_V1; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'EncryptionAlgorithm'; + } + + public function read($input) + { + return $this->_read('EncryptionAlgorithm', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('EncryptionAlgorithm', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/EncryptionWithColumnKey.php b/src/lib/parquet/src/Flow/Parquet/Thrift/EncryptionWithColumnKey.php new file mode 100644 index 000000000..216ca04b6 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/EncryptionWithColumnKey.php @@ -0,0 +1,70 @@ + [ + 'var' => 'path_in_schema', + 'isRequired' => true, + 'type' => TType::LST, + 'etype' => TType::STRING, + 'elem' => [ + 'type' => TType::STRING, + ], + ], + 2 => [ + 'var' => 'key_metadata', + 'isRequired' => false, + 'type' => TType::STRING, + ], + ]; + + public static $isValidate = false; + + /** + * Retrieval metadata of column encryption key *. + * + * @var string + */ + public $key_metadata; + + /** + * Column path in schema *. + * + * @var string[] + */ + public $path_in_schema; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'EncryptionWithColumnKey'; + } + + public function read($input) + { + return $this->_read('EncryptionWithColumnKey', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('EncryptionWithColumnKey', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/EncryptionWithFooterKey.php b/src/lib/parquet/src/Flow/Parquet/Thrift/EncryptionWithFooterKey.php new file mode 100644 index 000000000..e1ecdcbee --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/EncryptionWithFooterKey.php @@ -0,0 +1,38 @@ +_read('EncryptionWithFooterKey', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('EncryptionWithFooterKey', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/EnumType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/EnumType.php new file mode 100644 index 000000000..a2190ee35 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/EnumType.php @@ -0,0 +1,38 @@ +_read('EnumType', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('EnumType', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/FieldRepetitionType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/FieldRepetitionType.php new file mode 100644 index 000000000..521e27a5c --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/FieldRepetitionType.php @@ -0,0 +1,37 @@ + 'REQUIRED', + 1 => 'OPTIONAL', + 2 => 'REPEATED', + ]; +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/FileCryptoMetaData.php b/src/lib/parquet/src/Flow/Parquet/Thrift/FileCryptoMetaData.php new file mode 100644 index 000000000..41be9788c --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/FileCryptoMetaData.php @@ -0,0 +1,73 @@ + [ + 'var' => 'encryption_algorithm', + 'isRequired' => true, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\EncryptionAlgorithm', + ], + 2 => [ + 'var' => 'key_metadata', + 'isRequired' => false, + 'type' => TType::STRING, + ], + ]; + + public static $isValidate = false; + + /** + * Encryption algorithm. This field is only used for files + * with encrypted footer. Files with plaintext footer store algorithm id + * inside footer (FileMetaData structure). + * + * @var \Flow\Parquet\Thrift\EncryptionAlgorithm + */ + public $encryption_algorithm; + + /** + * Retrieval metadata of key used for encryption of footer, + * and (possibly) columns *. + * + * @var string + */ + public $key_metadata; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'FileCryptoMetaData'; + } + + public function read($input) + { + return $this->_read('FileCryptoMetaData', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('FileCryptoMetaData', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/FileMetaData.php b/src/lib/parquet/src/Flow/Parquet/Thrift/FileMetaData.php new file mode 100644 index 000000000..342c15c3a --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/FileMetaData.php @@ -0,0 +1,197 @@ + [ + 'var' => 'version', + 'isRequired' => true, + 'type' => TType::I32, + ], + 2 => [ + 'var' => 'schema', + 'isRequired' => true, + 'type' => TType::LST, + 'etype' => TType::STRUCT, + 'elem' => [ + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\SchemaElement', + ], + ], + 3 => [ + 'var' => 'num_rows', + 'isRequired' => true, + 'type' => TType::I64, + ], + 4 => [ + 'var' => 'row_groups', + 'isRequired' => true, + 'type' => TType::LST, + 'etype' => TType::STRUCT, + 'elem' => [ + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\RowGroup', + ], + ], + 5 => [ + 'var' => 'key_value_metadata', + 'isRequired' => false, + 'type' => TType::LST, + 'etype' => TType::STRUCT, + 'elem' => [ + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\KeyValue', + ], + ], + 6 => [ + 'var' => 'created_by', + 'isRequired' => false, + 'type' => TType::STRING, + ], + 7 => [ + 'var' => 'column_orders', + 'isRequired' => false, + 'type' => TType::LST, + 'etype' => TType::STRUCT, + 'elem' => [ + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\ColumnOrder', + ], + ], + 8 => [ + 'var' => 'encryption_algorithm', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\EncryptionAlgorithm', + ], + 9 => [ + 'var' => 'footer_signing_key_metadata', + 'isRequired' => false, + 'type' => TType::STRING, + ], + ]; + + public static $isValidate = false; + + /** + * Sort order used for the min_value and max_value fields in the Statistics + * objects and the min_values and max_values fields in the ColumnIndex + * objects of each column in this file. Sort orders are listed in the order + * matching the columns in the schema. The indexes are not necessary the same + * though, because only leaf nodes of the schema are represented in the list + * of sort orders. + * + * Without column_orders, the meaning of the min_value and max_value fields + * in the Statistics object and the ColumnIndex object is undefined. To ensure + * well-defined behaviour, if these fields are written to a Parquet file, + * column_orders must be written as well. + * + * The obsolete min and max fields in the Statistics object are always sorted + * by signed comparison regardless of column_orders. + * + * @var \Flow\Parquet\Thrift\ColumnOrder[] + */ + public $column_orders; + + /** + * String for application that wrote this file. This should be in the format + * version (build ). + * e.g. impala version 1.0 (build 6cf94d29b2b7115df4de2c06e2ab4326d721eb55). + * + * @var string + */ + public $created_by; + + /** + * Encryption algorithm. This field is set only in encrypted files + * with plaintext footer. Files with encrypted footer store algorithm id + * in FileCryptoMetaData structure. + * + * @var \Flow\Parquet\Thrift\EncryptionAlgorithm + */ + public $encryption_algorithm; + + /** + * Retrieval metadata of key used for signing the footer. + * Used only in encrypted files with plaintext footer. + * + * @var string + */ + public $footer_signing_key_metadata; + + /** + * Optional key/value metadata *. + * + * @var \Flow\Parquet\Thrift\KeyValue[] + */ + public $key_value_metadata; + + /** + * Number of rows in this file *. + * + * @var int + */ + public $num_rows; + + /** + * Row groups in this file *. + * + * @var \Flow\Parquet\Thrift\RowGroup[] + */ + public $row_groups; + + /** + * Parquet schema for this file. This schema contains metadata for all the columns. + * The schema is represented as a tree with a single root. The nodes of the tree + * are flattened to a list by doing a depth-first traversal. + * The column metadata contains the path in the schema for that column which can be + * used to map columns to nodes in the schema. + * The first element is the root *. + * + * @var \Flow\Parquet\Thrift\SchemaElement[] + */ + public $schema; + + /** + * Version of this file *. + * + * @var int + */ + public $version; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'FileMetaData'; + } + + public function read($input) + { + return $this->_read('FileMetaData', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('FileMetaData', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/IndexPageHeader.php b/src/lib/parquet/src/Flow/Parquet/Thrift/IndexPageHeader.php new file mode 100644 index 000000000..6b7553f2a --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/IndexPageHeader.php @@ -0,0 +1,38 @@ +_read('IndexPageHeader', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('IndexPageHeader', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/IntType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/IntType.php new file mode 100644 index 000000000..46af5332c --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/IntType.php @@ -0,0 +1,69 @@ + [ + 'var' => 'bitWidth', + 'isRequired' => true, + 'type' => TType::BYTE, + ], + 2 => [ + 'var' => 'isSigned', + 'isRequired' => true, + 'type' => TType::BOOL, + ], + ]; + + public static $isValidate = false; + + /** + * @var int + */ + public $bitWidth; + + /** + * @var bool + */ + public $isSigned; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'IntType'; + } + + public function read($input) + { + return $this->_read('IntType', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('IntType', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/JsonType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/JsonType.php new file mode 100644 index 000000000..8cce0ae5d --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/JsonType.php @@ -0,0 +1,43 @@ +_read('JsonType', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('JsonType', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/KeyValue.php b/src/lib/parquet/src/Flow/Parquet/Thrift/KeyValue.php new file mode 100644 index 000000000..ae80b90a3 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/KeyValue.php @@ -0,0 +1,65 @@ + [ + 'var' => 'key', + 'isRequired' => true, + 'type' => TType::STRING, + ], + 2 => [ + 'var' => 'value', + 'isRequired' => false, + 'type' => TType::STRING, + ], + ]; + + public static $isValidate = false; + + /** + * @var string + */ + public $key; + + /** + * @var string + */ + public $value; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'KeyValue'; + } + + public function read($input) + { + return $this->_read('KeyValue', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('KeyValue', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/ListType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/ListType.php new file mode 100644 index 000000000..3da6b7762 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/ListType.php @@ -0,0 +1,38 @@ +_read('ListType', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('ListType', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/LogicalType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/LogicalType.php new file mode 100644 index 000000000..93a187a54 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/LogicalType.php @@ -0,0 +1,192 @@ + [ + 'var' => 'STRING', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\StringType', + ], + 2 => [ + 'var' => 'MAP', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\MapType', + ], + 3 => [ + 'var' => 'LIST', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\ListType', + ], + 4 => [ + 'var' => 'ENUM', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\EnumType', + ], + 5 => [ + 'var' => 'DECIMAL', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\DecimalType', + ], + 6 => [ + 'var' => 'DATE', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\DateType', + ], + 7 => [ + 'var' => 'TIME', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\TimeType', + ], + 8 => [ + 'var' => 'TIMESTAMP', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\TimestampType', + ], + 10 => [ + 'var' => 'INTEGER', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\IntType', + ], + 11 => [ + 'var' => 'UNKNOWN', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\NullType', + ], + 12 => [ + 'var' => 'JSON', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\JsonType', + ], + 13 => [ + 'var' => 'BSON', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\BsonType', + ], + 14 => [ + 'var' => 'UUID', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\UUIDType', + ], + ]; + + public static $isValidate = false; + + /** + * @var \Flow\Parquet\Thrift\BsonType + */ + public $BSON; + + /** + * @var \Flow\Parquet\Thrift\DateType + */ + public $DATE; + + /** + * @var \Flow\Parquet\Thrift\DecimalType + */ + public $DECIMAL; + + /** + * @var \Flow\Parquet\Thrift\EnumType + */ + public $ENUM; + + /** + * @var \Flow\Parquet\Thrift\IntType + */ + public $INTEGER; + + /** + * @var \Flow\Parquet\Thrift\JsonType + */ + public $JSON; + + /** + * @var \Flow\Parquet\Thrift\ListType + */ + public $LIST; + + /** + * @var \Flow\Parquet\Thrift\MapType + */ + public $MAP; + + /** + * @var \Flow\Parquet\Thrift\StringType + */ + public $STRING; + + /** + * @var \Flow\Parquet\Thrift\TimeType + */ + public $TIME; + + /** + * @var \Flow\Parquet\Thrift\TimestampType + */ + public $TIMESTAMP; + + /** + * @var \Flow\Parquet\Thrift\NullType + */ + public $UNKNOWN; + + /** + * @var \Flow\Parquet\Thrift\UUIDType + */ + public $UUID; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'LogicalType'; + } + + public function read($input) + { + return $this->_read('LogicalType', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('LogicalType', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/MapType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/MapType.php new file mode 100644 index 000000000..4e9d22000 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/MapType.php @@ -0,0 +1,38 @@ +_read('MapType', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('MapType', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/MicroSeconds.php b/src/lib/parquet/src/Flow/Parquet/Thrift/MicroSeconds.php new file mode 100644 index 000000000..865654427 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/MicroSeconds.php @@ -0,0 +1,38 @@ +_read('MicroSeconds', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('MicroSeconds', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/MilliSeconds.php b/src/lib/parquet/src/Flow/Parquet/Thrift/MilliSeconds.php new file mode 100644 index 000000000..186ba3757 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/MilliSeconds.php @@ -0,0 +1,41 @@ +_read('MilliSeconds', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('MilliSeconds', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/NanoSeconds.php b/src/lib/parquet/src/Flow/Parquet/Thrift/NanoSeconds.php new file mode 100644 index 000000000..c9b5b3d14 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/NanoSeconds.php @@ -0,0 +1,38 @@ +_read('NanoSeconds', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('NanoSeconds', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/NullType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/NullType.php new file mode 100644 index 000000000..c007a8bc0 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/NullType.php @@ -0,0 +1,45 @@ +_read('NullType', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('NullType', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/OffsetIndex.php b/src/lib/parquet/src/Flow/Parquet/Thrift/OffsetIndex.php new file mode 100644 index 000000000..152b82f6b --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/OffsetIndex.php @@ -0,0 +1,60 @@ + [ + 'var' => 'page_locations', + 'isRequired' => true, + 'type' => TType::LST, + 'etype' => TType::STRUCT, + 'elem' => [ + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\PageLocation', + ], + ], + ]; + + public static $isValidate = false; + + /** + * PageLocations, ordered by increasing PageLocation.offset. It is required + * that page_locations[i].first_row_index < page_locations[i+1].first_row_index. + * + * @var \Flow\Parquet\Thrift\PageLocation[] + */ + public $page_locations; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'OffsetIndex'; + } + + public function read($input) + { + return $this->_read('OffsetIndex', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('OffsetIndex', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/PageEncodingStats.php b/src/lib/parquet/src/Flow/Parquet/Thrift/PageEncodingStats.php new file mode 100644 index 000000000..131321533 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/PageEncodingStats.php @@ -0,0 +1,83 @@ + [ + 'var' => 'page_type', + 'isRequired' => true, + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\PageType', + ], + 2 => [ + 'var' => 'encoding', + 'isRequired' => true, + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\Encoding', + ], + 3 => [ + 'var' => 'count', + 'isRequired' => true, + 'type' => TType::I32, + ], + ]; + + public static $isValidate = false; + + /** + * number of pages of this type with this encoding *. + * + * @var int + */ + public $count; + + /** + * encoding of the page *. + * + * @var int + */ + public $encoding; + + /** + * the page type (data/dic/...) *. + * + * @var int + */ + public $page_type; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'PageEncodingStats'; + } + + public function read($input) + { + return $this->_read('PageEncodingStats', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('PageEncodingStats', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/PageHeader.php b/src/lib/parquet/src/Flow/Parquet/Thrift/PageHeader.php new file mode 100644 index 000000000..74eeef1ea --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/PageHeader.php @@ -0,0 +1,150 @@ + [ + 'var' => 'type', + 'isRequired' => true, + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\PageType', + ], + 2 => [ + 'var' => 'uncompressed_page_size', + 'isRequired' => true, + 'type' => TType::I32, + ], + 3 => [ + 'var' => 'compressed_page_size', + 'isRequired' => true, + 'type' => TType::I32, + ], + 4 => [ + 'var' => 'crc', + 'isRequired' => false, + 'type' => TType::I32, + ], + 5 => [ + 'var' => 'data_page_header', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\DataPageHeader', + ], + 6 => [ + 'var' => 'index_page_header', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\IndexPageHeader', + ], + 7 => [ + 'var' => 'dictionary_page_header', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\DictionaryPageHeader', + ], + 8 => [ + 'var' => 'data_page_header_v2', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\DataPageHeaderV2', + ], + ]; + + public static $isValidate = false; + + /** + * Compressed (and potentially encrypted) page size in bytes, not including this header *. + * + * @var int + */ + public $compressed_page_size; + + /** + * The 32-bit CRC checksum for the page, to be be calculated as follows:. + * + * - The standard CRC32 algorithm is used (with polynomial 0x04C11DB7, + * the same as in e.g. GZip). + * - All page types can have a CRC (v1 and v2 data pages, dictionary pages, + * etc.). + * - The CRC is computed on the serialization binary representation of the page + * (as written to disk), excluding the page header. For example, for v1 + * data pages, the CRC is computed on the concatenation of repetition levels, + * definition levels and column values (optionally compressed, optionally + * encrypted). + * - The CRC computation therefore takes place after any compression + * and encryption steps, if any. + * + * If enabled, this allows for disabling checksumming in HDFS if only a few + * pages need to be read. + * + * @var int + */ + public $crc; + + /** + * @var \Flow\Parquet\Thrift\DataPageHeader + */ + public $data_page_header; + + /** + * @var \Flow\Parquet\Thrift\DataPageHeaderV2 + */ + public $data_page_header_v2; + + /** + * @var \Flow\Parquet\Thrift\DictionaryPageHeader + */ + public $dictionary_page_header; + + /** + * @var \Flow\Parquet\Thrift\IndexPageHeader + */ + public $index_page_header; + + /** + * the type of the page: indicates which of the *_header fields is set *. + * + * @var int + */ + public $type; + + /** + * Uncompressed page size in bytes (not including this header) *. + * + * @var int + */ + public $uncompressed_page_size; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'PageHeader'; + } + + public function read($input) + { + return $this->_read('PageHeader', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('PageHeader', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/PageLocation.php b/src/lib/parquet/src/Flow/Parquet/Thrift/PageLocation.php new file mode 100644 index 000000000..c3cd40d17 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/PageLocation.php @@ -0,0 +1,80 @@ + [ + 'var' => 'offset', + 'isRequired' => true, + 'type' => TType::I64, + ], + 2 => [ + 'var' => 'compressed_page_size', + 'isRequired' => true, + 'type' => TType::I32, + ], + 3 => [ + 'var' => 'first_row_index', + 'isRequired' => true, + 'type' => TType::I64, + ], + ]; + + public static $isValidate = false; + + /** + * Size of the page, including header. Sum of compressed_page_size and header + * length. + * + * @var int + */ + public $compressed_page_size; + + /** + * Index within the RowGroup of the first row of the page; this means pages + * change on record boundaries (r = 0). + * + * @var int + */ + public $first_row_index; + + /** + * Offset of the page in the file *. + * + * @var int + */ + public $offset; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'PageLocation'; + } + + public function read($input) + { + return $this->_read('PageLocation', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('PageLocation', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/PageType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/PageType.php new file mode 100644 index 000000000..2fb1a5295 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/PageType.php @@ -0,0 +1,27 @@ + 'DATA_PAGE', + 1 => 'INDEX_PAGE', + 2 => 'DICTIONARY_PAGE', + 3 => 'DATA_PAGE_V2', + ]; +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/RowGroup.php b/src/lib/parquet/src/Flow/Parquet/Thrift/RowGroup.php new file mode 100644 index 000000000..028db7770 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/RowGroup.php @@ -0,0 +1,140 @@ + [ + 'var' => 'columns', + 'isRequired' => true, + 'type' => TType::LST, + 'etype' => TType::STRUCT, + 'elem' => [ + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\ColumnChunk', + ], + ], + 2 => [ + 'var' => 'total_byte_size', + 'isRequired' => true, + 'type' => TType::I64, + ], + 3 => [ + 'var' => 'num_rows', + 'isRequired' => true, + 'type' => TType::I64, + ], + 4 => [ + 'var' => 'sorting_columns', + 'isRequired' => false, + 'type' => TType::LST, + 'etype' => TType::STRUCT, + 'elem' => [ + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\SortingColumn', + ], + ], + 5 => [ + 'var' => 'file_offset', + 'isRequired' => false, + 'type' => TType::I64, + ], + 6 => [ + 'var' => 'total_compressed_size', + 'isRequired' => false, + 'type' => TType::I64, + ], + 7 => [ + 'var' => 'ordinal', + 'isRequired' => false, + 'type' => TType::I16, + ], + ]; + + public static $isValidate = false; + + /** + * Metadata for each column chunk in this row group. + * This list must have the same order as the SchemaElement list in FileMetaData. + * + * @var \Flow\Parquet\Thrift\ColumnChunk[] + */ + public $columns; + + /** + * Byte offset from beginning of file to first page (data or dictionary) + * in this row group *. + * + * @var int + */ + public $file_offset; + + /** + * Number of rows in this row group *. + * + * @var int + */ + public $num_rows; + + /** + * Row group ordinal in the file *. + * + * @var int + */ + public $ordinal; + + /** + * If set, specifies a sort ordering of the rows in this RowGroup. + * The sorting columns can be a subset of all the columns. + * + * @var \Flow\Parquet\Thrift\SortingColumn[] + */ + public $sorting_columns; + + /** + * Total byte size of all the uncompressed column data in this row group *. + * + * @var int + */ + public $total_byte_size; + + /** + * Total byte size of all compressed (and potentially encrypted) column data + * in this row group *. + * + * @var int + */ + public $total_compressed_size; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'RowGroup'; + } + + public function read($input) + { + return $this->_read('RowGroup', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('RowGroup', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/SchemaElement.php b/src/lib/parquet/src/Flow/Parquet/Thrift/SchemaElement.php new file mode 100644 index 000000000..32f2bc8fc --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/SchemaElement.php @@ -0,0 +1,187 @@ + [ + 'var' => 'type', + 'isRequired' => false, + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\Type', + ], + 2 => [ + 'var' => 'type_length', + 'isRequired' => false, + 'type' => TType::I32, + ], + 3 => [ + 'var' => 'repetition_type', + 'isRequired' => false, + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\FieldRepetitionType', + ], + 4 => [ + 'var' => 'name', + 'isRequired' => true, + 'type' => TType::STRING, + ], + 5 => [ + 'var' => 'num_children', + 'isRequired' => false, + 'type' => TType::I32, + ], + 6 => [ + 'var' => 'converted_type', + 'isRequired' => false, + 'type' => TType::I32, + 'class' => '\Flow\Parquet\Thrift\ConvertedType', + ], + 7 => [ + 'var' => 'scale', + 'isRequired' => false, + 'type' => TType::I32, + ], + 8 => [ + 'var' => 'precision', + 'isRequired' => false, + 'type' => TType::I32, + ], + 9 => [ + 'var' => 'field_id', + 'isRequired' => false, + 'type' => TType::I32, + ], + 10 => [ + 'var' => 'logicalType', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\LogicalType', + ], + ]; + + public static $isValidate = false; + + /** + * DEPRECATED: When the schema is the result of a conversion from another model. + * Used to record the original type to help with cross conversion. + * + * This is superseded by logicalType. + * + * @var int + */ + public $converted_type; + + /** + * When the original schema supports field ids, this will save the + * original field id in the parquet schema. + * + * @var int + */ + public $field_id; + + /** + * The logical type of this SchemaElement. + * + * LogicalType replaces ConvertedType, but ConvertedType is still required + * for some logical types to ensure forward-compatibility in format v1. + * + * @var \Flow\Parquet\Thrift\LogicalType + */ + public $logicalType; + + /** + * Name of the field in the schema. + * + * @var string + */ + public $name; + + /** + * Nested fields. Since thrift does not support nested fields, + * the nesting is flattened to a single list by a depth-first traversal. + * The children count is used to construct the nested relationship. + * This field is not set when the element is a primitive type. + * + * @var int + */ + public $num_children; + + /** + * @var int + */ + public $precision; + + /** + * repetition of the field. The root of the schema does not have a repetition_type. + * All other nodes must have one. + * + * @var int + */ + public $repetition_type; + + /** + * DEPRECATED: Used when this column contains decimal data. + * See the DECIMAL converted type for more details. + * + * This is superseded by using the DecimalType annotation in logicalType. + * + * @var int + */ + public $scale; + + /** + * Data type for this field. Not set if the current element is a non-leaf node. + * + * @var int + */ + public $type; + + /** + * If type is FIXED_LEN_BYTE_ARRAY, this is the byte length of the values. + * Otherwise, if specified, this is the maximum bit length to store any of the values. + * (e.g. a low cardinality INT col could have this set to 3). Note that this is + * in the schema, and therefore fixed for the entire file. + * + * @var int + */ + public $type_length; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'SchemaElement'; + } + + public function read($input) + { + return $this->_read('SchemaElement', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('SchemaElement', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/SortingColumn.php b/src/lib/parquet/src/Flow/Parquet/Thrift/SortingColumn.php new file mode 100644 index 000000000..d0005a561 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/SortingColumn.php @@ -0,0 +1,82 @@ + [ + 'var' => 'column_idx', + 'isRequired' => true, + 'type' => TType::I32, + ], + 2 => [ + 'var' => 'descending', + 'isRequired' => true, + 'type' => TType::BOOL, + ], + 3 => [ + 'var' => 'nulls_first', + 'isRequired' => true, + 'type' => TType::BOOL, + ], + ]; + + public static $isValidate = false; + + /** + * The column index (in this row group) *. + * + * @var int + */ + public $column_idx; + + /** + * If true, indicates this column is sorted in descending order. *. + * + * @var bool + */ + public $descending; + + /** + * If true, nulls will come before non-null values, otherwise, + * nulls go at the end. + * + * @var bool + */ + public $nulls_first; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'SortingColumn'; + } + + public function read($input) + { + return $this->_read('SortingColumn', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('SortingColumn', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/SplitBlockAlgorithm.php b/src/lib/parquet/src/Flow/Parquet/Thrift/SplitBlockAlgorithm.php new file mode 100644 index 000000000..c0281c50b --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/SplitBlockAlgorithm.php @@ -0,0 +1,41 @@ +_read('SplitBlockAlgorithm', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('SplitBlockAlgorithm', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/Statistics.php b/src/lib/parquet/src/Flow/Parquet/Thrift/Statistics.php new file mode 100644 index 000000000..4980a672f --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/Statistics.php @@ -0,0 +1,127 @@ + [ + 'var' => 'max', + 'isRequired' => false, + 'type' => TType::STRING, + ], + 2 => [ + 'var' => 'min', + 'isRequired' => false, + 'type' => TType::STRING, + ], + 3 => [ + 'var' => 'null_count', + 'isRequired' => false, + 'type' => TType::I64, + ], + 4 => [ + 'var' => 'distinct_count', + 'isRequired' => false, + 'type' => TType::I64, + ], + 5 => [ + 'var' => 'max_value', + 'isRequired' => false, + 'type' => TType::STRING, + ], + 6 => [ + 'var' => 'min_value', + 'isRequired' => false, + 'type' => TType::STRING, + ], + ]; + + public static $isValidate = false; + + /** + * count of distinct values occurring. + * + * @var int + */ + public $distinct_count; + + /** + * DEPRECATED: min and max value of the column. Use min_value and max_value. + * + * Values are encoded using PLAIN encoding, except that variable-length byte + * arrays do not include a length prefix. + * + * These fields encode min and max values determined by signed comparison + * only. New files should use the correct order for a column's logical type + * and store the values in the min_value and max_value fields. + * + * To support older readers, these may be set when the column order is + * signed. + * + * @var string + */ + public $max; + + /** + * Min and max values for the column, determined by its ColumnOrder. + * + * Values are encoded using PLAIN encoding, except that variable-length byte + * arrays do not include a length prefix. + * + * @var string + */ + public $max_value; + + /** + * @var string + */ + public $min; + + /** + * @var string + */ + public $min_value; + + /** + * count of null value in the column. + * + * @var int + */ + public $null_count; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'Statistics'; + } + + public function read($input) + { + return $this->_read('Statistics', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('Statistics', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/StringType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/StringType.php new file mode 100644 index 000000000..eff3be17c --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/StringType.php @@ -0,0 +1,41 @@ +_read('StringType', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('StringType', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/TimeType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/TimeType.php new file mode 100644 index 000000000..21af2eff8 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/TimeType.php @@ -0,0 +1,68 @@ + [ + 'var' => 'isAdjustedToUTC', + 'isRequired' => true, + 'type' => TType::BOOL, + ], + 2 => [ + 'var' => 'unit', + 'isRequired' => true, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\TimeUnit', + ], + ]; + + public static $isValidate = false; + + /** + * @var bool + */ + public $isAdjustedToUTC; + + /** + * @var \Flow\Parquet\Thrift\TimeUnit + */ + public $unit; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'TimeType'; + } + + public function read($input) + { + return $this->_read('TimeType', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('TimeType', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/TimeUnit.php b/src/lib/parquet/src/Flow/Parquet/Thrift/TimeUnit.php new file mode 100644 index 000000000..489f54d22 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/TimeUnit.php @@ -0,0 +1,75 @@ + [ + 'var' => 'MILLIS', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\MilliSeconds', + ], + 2 => [ + 'var' => 'MICROS', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\MicroSeconds', + ], + 3 => [ + 'var' => 'NANOS', + 'isRequired' => false, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\NanoSeconds', + ], + ]; + + public static $isValidate = false; + + /** + * @var \Flow\Parquet\Thrift\MicroSeconds + */ + public $MICROS; + + /** + * @var \Flow\Parquet\Thrift\MilliSeconds + */ + public $MILLIS; + + /** + * @var \Flow\Parquet\Thrift\NanoSeconds + */ + public $NANOS; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'TimeUnit'; + } + + public function read($input) + { + return $this->_read('TimeUnit', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('TimeUnit', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/TimestampType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/TimestampType.php new file mode 100644 index 000000000..0a34398a1 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/TimestampType.php @@ -0,0 +1,68 @@ + [ + 'var' => 'isAdjustedToUTC', + 'isRequired' => true, + 'type' => TType::BOOL, + ], + 2 => [ + 'var' => 'unit', + 'isRequired' => true, + 'type' => TType::STRUCT, + 'class' => '\Flow\Parquet\Thrift\TimeUnit', + ], + ]; + + public static $isValidate = false; + + /** + * @var bool + */ + public $isAdjustedToUTC; + + /** + * @var \Flow\Parquet\Thrift\TimeUnit + */ + public $unit; + + public function __construct($vals = null) + { + if (\is_array($vals)) { + parent::__construct(self::$_TSPEC, $vals); + } + } + + public function getName() + { + return 'TimestampType'; + } + + public function read($input) + { + return $this->_read('TimestampType', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('TimestampType', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/Type.php b/src/lib/parquet/src/Flow/Parquet/Thrift/Type.php new file mode 100644 index 000000000..c8875c004 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/Type.php @@ -0,0 +1,46 @@ + 'BOOLEAN', + 1 => 'INT32', + 2 => 'INT64', + 3 => 'INT96', + 4 => 'FLOAT', + 5 => 'DOUBLE', + 6 => 'BYTE_ARRAY', + 7 => 'FIXED_LEN_BYTE_ARRAY', + ]; +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/TypeDefinedOrder.php b/src/lib/parquet/src/Flow/Parquet/Thrift/TypeDefinedOrder.php new file mode 100644 index 000000000..35365cba3 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/TypeDefinedOrder.php @@ -0,0 +1,41 @@ +_read('TypeDefinedOrder', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('TypeDefinedOrder', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/UUIDType.php b/src/lib/parquet/src/Flow/Parquet/Thrift/UUIDType.php new file mode 100644 index 000000000..e52429462 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/UUIDType.php @@ -0,0 +1,38 @@ +_read('UUIDType', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('UUIDType', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/Uncompressed.php b/src/lib/parquet/src/Flow/Parquet/Thrift/Uncompressed.php new file mode 100644 index 000000000..68f8ef896 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/Uncompressed.php @@ -0,0 +1,41 @@ +_read('Uncompressed', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('Uncompressed', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/Thrift/XxHash.php b/src/lib/parquet/src/Flow/Parquet/Thrift/XxHash.php new file mode 100644 index 000000000..f587bb7d0 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/Thrift/XxHash.php @@ -0,0 +1,42 @@ +_read('XxHash', self::$_TSPEC, $input); + } + + public function write($output) + { + return $this->_write('XxHash', self::$_TSPEC, $output); + } +} diff --git a/src/lib/parquet/src/Flow/Parquet/functions.php b/src/lib/parquet/src/Flow/Parquet/functions.php new file mode 100644 index 000000000..4168a0cc8 --- /dev/null +++ b/src/lib/parquet/src/Flow/Parquet/functions.php @@ -0,0 +1,46 @@ + &$value) { + if (\is_array($value) && isset($merged[$key]) && \is_array($merged[$key])) { + $merged[$key] = array_merge_recursive($merged[$key], $value); + } else { + $merged[$key] = $value; + } + } + + return $merged; +} + +/** + * @psalm-suppress MixedArrayOffset + * @psalm-suppress MixedAssignment + */ +function array_combine_recursive(array $keys, array $values) : array +{ + $result = []; + + foreach ($keys as $keyIndex => $keyValue) { + $value = $values[$keyIndex] ?? null; + + if (\is_array($keyValue) && \is_array($value)) { + $result[] = array_combine_recursive($keyValue, $value); + } else { + $result[$keyValue] = $value; + } + } + + return $result; +} diff --git a/src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/lists.json b/src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/lists.json new file mode 100644 index 000000000..958775884 --- /dev/null +++ b/src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/lists.json @@ -0,0 +1 @@ +{"schema":{"type":"message","children":{"list":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"INT32","optional":true}}}}},"list_nullable":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"INT32","optional":true}}}}},"list_mixed_types":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"group","optional":true,"children":{"int":{"type":"INT32","optional":true},"string":{"type":"BYTE_ARRAY (STRING)","optional":true},"bool":{"type":"BOOLEAN","optional":true}}}}}}},"list_nested":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"INT32","optional":true}}}}}}}}}}}}}}}} \ No newline at end of file diff --git a/src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/lists.parquet b/src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/lists.parquet new file mode 100644 index 0000000000000000000000000000000000000000..d68ed70497ef171225f7942b35552d138c2a4f12 GIT binary patch literal 4772 zcmc&&dstIP7Qabu5$1S1r}H^0kllW`6&uaOz4iyNKL(eqo$yqcS}Zb zZR~*i|kY;}&?YMTmLvgxMB#}3K%8Sx9Z51pZkVa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U>Si9*gU(f$K82v5GWbY{4-;U9il=HNQJH1o9VN&4V&At zvtoCW$6qZV>)5mbb}|(^a9prr_v`P!T0kMT->lh19i|rp2mlhWVV~C_dwO7hY_;<{ zw3BN0Z)H0gL4mOcr@#0FD|Vad&K9hK?yT6o%s*RzTyR=?+BNEbJW>3Am@^IkpC{|W z|GoUw|2nJm@8^WV|Ka3A`2Q;7?w?Ok`yZxy!T;&(Bl!O;3kUwMBnZI&-B-l$|MlA} z_`mjM1OER<&QxMI}A`Y;h!ii~;@8AG`F+fWXBSUFvsq2bt9gARJ zNV&m_7j*`OLTLj3!Alv1@vL`T{G(X6J29_0Ycv+Aq zls)(*k7bP?d;}VRvW+k|w=nQWqMRdO`|hf>1Qd+wpv2m9}!$Ig$X2OCf_!rT_z-0~p50FEe4TPz4z(0?rz zfD%}%pygz$t78Gk>uM@5XKgC44OGf%f=dfN{Df2!91kc<%k0np*8K8zZdjhN>xz!^xdit_v= zpCfh<1)z3Y6#*2s(pO@S(`v0Vl&S+kw`(Axi26T#>e-His`iP~+&L}4f z5OKP4d;CXz)ByVe_JanJQYgmuksn0t@Xz0_qP6`K>Lw)GIh}8#TvEZU;Tg5tNvB~N&lPw0bLcA z-bdALw=eMgOMcXuza|AH!|D?N1y*LwZKv?3@qh8>qlz8H5-@Vmv7$l${PWrx9|B`? zGI4QsH+MszotzLRE-sFqOdjSguGWqYOsDxy@tooTf-N9e{jWa|JK$x32JlzZ{|`pc BjBx+} literal 0 HcmV?d00001 diff --git a/src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/structs.json b/src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/structs.json new file mode 100644 index 000000000..55f8676d8 --- /dev/null +++ b/src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/structs.json @@ -0,0 +1 @@ +{"schema":{"type":"message","children":{"struct_flat":{"type":"group","optional":true,"children":{"string":{"type":"BYTE_ARRAY (STRING)","optional":true},"string_nullable":{"type":"BYTE_ARRAY (STRING)","optional":true},"int":{"type":"INT32","optional":true},"int_nullable":{"type":"INT32","optional":true},"bool":{"type":"BOOLEAN","optional":true},"bool_nullable":{"type":"BOOLEAN","optional":true},"list_of_ints":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"INT32","optional":true}}}}},"list_of_strings":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"BYTE_ARRAY (STRING)","optional":true}}}}},"map_of_string_int":{"type":"group","optional":true,"children":{"key_value":{"type":"group","optional":false,"children":{"key":{"type":"BYTE_ARRAY (STRING)","optional":false},"value":{"type":"INT32","optional":true}}}}},"map_of_int_int":{"type":"group","optional":true,"children":{"key_value":{"type":"group","optional":false,"children":{"key":{"type":"INT32","optional":false},"value":{"type":"INT32","optional":true}}}}}}},"struct_nested":{"type":"group","optional":true,"children":{"string":{"type":"BYTE_ARRAY (STRING)","optional":true},"struct_flat":{"type":"group","optional":true,"children":{"int":{"type":"INT32","optional":true},"list_of_ints":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"INT32","optional":true}}}}},"map_of_string_int":{"type":"group","optional":true,"children":{"key_value":{"type":"group","optional":false,"children":{"key":{"type":"BYTE_ARRAY (STRING)","optional":false},"value":{"type":"INT32","optional":true}}}}}}}}},"struct_nested_with_list_of_lists":{"type":"group","optional":true,"children":{"string":{"type":"BYTE_ARRAY (STRING)","optional":true},"struct":{"type":"group","optional":true,"children":{"int":{"type":"INT32","optional":true},"list_of_list_of_ints":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"INT32","optional":true}}}}}}}}}}}}},"struct_nested_with_list_of_maps":{"type":"group","optional":true,"children":{"string":{"type":"BYTE_ARRAY (STRING)","optional":true},"struct":{"type":"group","optional":true,"children":{"int":{"type":"INT32","optional":true},"list_of_map_of_string_int":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"group","optional":true,"children":{"key_value":{"type":"group","optional":false,"children":{"key":{"type":"BYTE_ARRAY (STRING)","optional":false},"value":{"type":"INT32","optional":true}}}}}}}}}}}}},"struct_nested_with_map_of_list_of_ints":{"type":"group","optional":true,"children":{"string":{"type":"BYTE_ARRAY (STRING)","optional":true},"struct":{"type":"group","optional":true,"children":{"int":{"type":"INT32","optional":true},"map_of_int_list_of_string":{"type":"group","optional":true,"children":{"key_value":{"type":"group","optional":false,"children":{"key":{"type":"INT32","optional":false},"value":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"BYTE_ARRAY (STRING)","optional":true}}}}}}}}}}}}},"struct_nested_with_map_of_string_map_of_string_string":{"type":"group","optional":true,"children":{"string":{"type":"BYTE_ARRAY (STRING)","optional":true},"struct":{"type":"group","optional":true,"children":{"int":{"type":"INT32","optional":true},"map_of_string_map_of_string_string":{"type":"group","optional":true,"children":{"key_value":{"type":"group","optional":false,"children":{"key":{"type":"BYTE_ARRAY (STRING)","optional":false},"value":{"type":"group","optional":true,"children":{"key_value":{"type":"group","optional":false,"children":{"key":{"type":"BYTE_ARRAY (STRING)","optional":false},"value":{"type":"BYTE_ARRAY (STRING)","optional":true}}}}}}}}}}}}},"struct_with_list_and_map_of_structs":{"type":"group","optional":true,"children":{"string":{"type":"BYTE_ARRAY (STRING)","optional":true},"struct":{"type":"group","optional":true,"children":{"int":{"type":"INT32","optional":true},"list_of_structs":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"group","optional":true,"children":{"int":{"type":"INT32","optional":true},"list":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"INT32","optional":true}}}}}}}}}}},"map_of_string_structs":{"type":"group","optional":true,"children":{"key_value":{"type":"group","optional":false,"children":{"key":{"type":"BYTE_ARRAY (STRING)","optional":false},"value":{"type":"group","optional":true,"children":{"int":{"type":"INT32","optional":true},"list":{"type":"group","optional":true,"children":{"list":{"type":"group","optional":false,"children":{"element":{"type":"INT32","optional":true}}}}}}}}}}}}}}},"struct_deeply_nested":{"type":"group","optional":true,"children":{"struct_0":{"type":"group","optional":true,"children":{"int":{"type":"INT32","optional":true},"struct_1":{"type":"group","optional":true,"children":{"string":{"type":"BYTE_ARRAY (STRING)","optional":true},"struct_2":{"type":"group","optional":true,"children":{"bool":{"type":"BOOLEAN","optional":true},"struct_3":{"type":"group","optional":true,"children":{"float":{"type":"FLOAT","optional":true},"struct_4":{"type":"group","optional":true,"children":{"string":{"type":"BYTE_ARRAY (STRING)","optional":true},"json":{"type":"BYTE_ARRAY (STRING)","optional":true}}}}}}}}}}}}}}}} \ No newline at end of file diff --git a/src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/structs.parquet b/src/lib/parquet/tests/Flow/Parquet/Tests/Fixtures/structs.parquet new file mode 100644 index 0000000000000000000000000000000000000000..94c4f97ea443c341ff4d24a77f149bef0ec440d7 GIT binary patch literal 33663 zcmeHP2V7IfA5TIUA}&f|RH%yb1X03}Sx8I>dl)cGEi()u4B22sz*)tORB)lL|wok>A zR!gRlv`M7?vouKP=L@eB1O2HZwRqKwl9w199b9r|KsJM#{APOj*h#-VZO*dK&Hah} z6YKH{=9`zZ^_qmeUv69C&=hqg;K1_3OL{r?jnZ8`+w2^_rzV$UsG+)YfXY;(Eo5Eh{H?+iieNo(@xIH1;7K@xW{hqjcY2uN)FLJBOl3j=O zom*R;a#Uou;?(*y_btI&>o;foaxdqnhHY6|p#O%xqs9xtC$>vXm!{RnlBCwNk6~9p zQ+i}tXtXFiO%11yMy1!1>GgDag&KBC1=DDii$24EhDkIEN03x8$W@^&rP&{cu zMTOT5)TWsABvsd5w>}cR(=B9jxv56Oo2mOUEY{9FcmB^mv-hu<`*^oqWBII*%1sZ} zec^3)Q)9|V{9o@z%GYIG)ADs((LV;oF-$`%e;}V?fc}jR)AY-3KiAXA8mk>;Prv=# zepeU%qi$}qX9pJdd%Vwzvzlp;8gh7Jy6x6KX%9(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plf%=E>3ZIk9(8P0t;{zcBu*SgELtyW)GQgpP2(dpz-y?m%3iwjB%z7{01U)A) z1|)~4j8BhB8y=aQJUl!lB`I@2MpR1bxTM4ZW)>!getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/lists.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('list')->type()); + $this->assertEquals('LIST', $file->metadata()->schema()->get('list')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['list']) as $row) { + $this->assertContainsOnly('int', $row['list']); + $this->assertCount(3, $row['list']); + $count++; + } + + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_list_column_with_limit() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/lists.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('list')->type()); + $this->assertEquals('LIST', $file->metadata()->schema()->get('list')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['list'], $limit = 50) as $row) { + $this->assertContainsOnly('int', $row['list']); + $this->assertCount(3, $row['list']); + $count++; + } + + $this->assertSame($limit, $count); + } + + public function test_reading_list_nested_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/lists.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('list_nested')->type()); + $this->assertEquals('LIST', $file->metadata()->schema()->get('list_nested')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['list_nested']) as $row) { + $this->assertIsArray($row['list_nested']); + $this->assertIsList($row['list_nested']); + $this->assertIsArray($row['list_nested'][0]); + $this->assertIsList($row['list_nested'][0]); + $this->assertIsArray($row['list_nested'][0][0]); + + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_list_nullable_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/lists.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('list_nullable')->type()); + $this->assertEquals('LIST', $file->metadata()->schema()->get('list_nullable')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['list_nullable']) as $rowIndex => $row) { + if ($rowIndex % 2 === 0) { + $this->assertContainsOnly('int', $row['list_nullable']); + $this->assertCount(3, $row['list_nullable']); + } else { + $this->assertNull($row['list_nullable']); + } + $count++; + } + + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_list_of_structures_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/lists.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('list_mixed_types')->type()); + $this->assertEquals('LIST', $file->metadata()->schema()->get('list_mixed_types')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['list_mixed_types']) as $row) { + $this->assertIsArray($row['list_mixed_types']); + $this->assertCount(4, $row['list_mixed_types']); + $this->assertArrayHasKey('int', $row['list_mixed_types'][0]); + $this->assertArrayHasKey('string', $row['list_mixed_types'][0]); + $this->assertArrayHasKey('bool', $row['list_mixed_types'][0]); + $this->assertArrayHasKey('int', $row['list_mixed_types'][1]); + $this->assertArrayHasKey('string', $row['list_mixed_types'][1]); + $this->assertArrayHasKey('bool', $row['list_mixed_types'][1]); + $this->assertArrayHasKey('int', $row['list_mixed_types'][2]); + $this->assertArrayHasKey('string', $row['list_mixed_types'][2]); + $this->assertArrayHasKey('bool', $row['list_mixed_types'][2]); + $this->assertArrayHasKey('int', $row['list_mixed_types'][3]); + $this->assertArrayHasKey('string', $row['list_mixed_types'][3]); + $this->assertArrayHasKey('bool', $row['list_mixed_types'][3]); + $count++; + } + + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } +} diff --git a/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/MapsReadingTest.php b/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/MapsReadingTest.php new file mode 100644 index 000000000..f713282d4 --- /dev/null +++ b/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/MapsReadingTest.php @@ -0,0 +1,199 @@ +getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/maps.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('map')->type()); + $this->assertEquals('MAP', $file->metadata()->schema()->get('map')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['map']) as $row) { + $this->assertIsString(\array_key_first($row['map'])); + $this->assertIsInt($row['map'][\array_key_first($row['map'])]); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_map_nullable_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/maps.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('map_nullable')->type()); + $this->assertEquals('MAP', $file->metadata()->schema()->get('map_nullable')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['map_nullable']) as $rowIndex => $row) { + if ($rowIndex % 2 === 0) { + $this->assertIsString(\array_key_first($row['map_nullable'])); + $this->assertIsInt($row['map_nullable'][\array_key_first($row['map_nullable'])]); + } else { + $this->assertNull($row['map_nullable']); + } + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_map_of_complex_lists() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/maps.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('map_of_complex_lists')->type()); + $this->assertEquals('MAP', $file->metadata()->schema()->get('map_of_complex_lists')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['map_of_complex_lists']) as $row) { + $this->assertIsArray($row['map_of_complex_lists']); + $this->assertIsArray($row['map_of_complex_lists']['key_0']); + $this->assertIsString($row['map_of_complex_lists']['key_0']['string'][0]); + $this->assertIsInt($row['map_of_complex_lists']['key_0']['int'][0]); + $this->assertIsBool($row['map_of_complex_lists']['key_0']['bool'][0]); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_map_of_list_of_map_of_lists() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/maps.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('map_of_list_of_map_of_lists')->type()); + $this->assertEquals('MAP', $file->metadata()->schema()->get('map_of_list_of_map_of_lists')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['map_of_list_of_map_of_lists']) as $row) { + $this->assertIsArray($row['map_of_list_of_map_of_lists']); + $this->assertIsArray($row['map_of_list_of_map_of_lists']['key_0']); + $this->assertIsArray($row['map_of_list_of_map_of_lists']['key_0'][0]); + $this->assertIsArray($row['map_of_list_of_map_of_lists']['key_0'][0]['string_0_0_0']); + $this->assertIsList($row['map_of_list_of_map_of_lists']['key_0'][0]['string_0_0_0']); + $this->assertIsInt($row['map_of_list_of_map_of_lists']['key_0'][0]['string_0_0_0'][0]); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_map_of_lists() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/maps.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('map_of_lists')->type()); + $this->assertEquals('MAP', $file->metadata()->schema()->get('map_of_lists')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['map_of_lists']) as $row) { + $this->assertIsArray($row['map_of_lists']); + $this->assertIsArray($row['map_of_lists']['key_0']); + $this->assertIsList($row['map_of_lists']['key_0']); + $this->assertIsInt($row['map_of_lists']['key_0'][0]); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_map_of_maps_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/maps.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('map_of_maps')->type()); + $this->assertEquals('MAP', $file->metadata()->schema()->get('map_of_maps')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['map_of_maps']) as $row) { + $this->assertIsArray($row['map_of_maps']); + $this->assertIsArray($row['map_of_maps']['outer_key_0']); + $this->assertIsInt($row['map_of_maps']['outer_key_0']['inner_key_0']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_map_of_struct_of_structs_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/maps.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('map_of_struct_of_structs')->type()); + $this->assertEquals('MAP', $file->metadata()->schema()->get('map_of_struct_of_structs')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['map_of_struct_of_structs']) as $row) { + $this->assertIsArray($row['map_of_struct_of_structs']); + $this->assertIsArray($row['map_of_struct_of_structs']['key_0']); + $this->assertIsInt($row['map_of_struct_of_structs']['key_0']['struct']['nested_struct']['int']); + $this->assertIsString($row['map_of_struct_of_structs']['key_0']['struct']['nested_struct']['string']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_map_of_struct_of_structs_column_with_limit() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/maps.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('map_of_struct_of_structs')->type()); + $this->assertEquals('MAP', $file->metadata()->schema()->get('map_of_struct_of_structs')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['map_of_struct_of_structs'], $limit = 50) as $row) { + $this->assertIsArray($row['map_of_struct_of_structs']); + $this->assertIsArray($row['map_of_struct_of_structs']['key_0']); + $this->assertIsInt($row['map_of_struct_of_structs']['key_0']['struct']['nested_struct']['int']); + $this->assertIsString($row['map_of_struct_of_structs']['key_0']['struct']['nested_struct']['string']); + $count++; + } + $this->assertSame($limit, $count); + } + + public function test_reading_map_of_structs_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/maps.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('map_of_structs')->type()); + $this->assertEquals('MAP', $file->metadata()->schema()->get('map_of_structs')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['map_of_structs']) as $row) { + $this->assertIsArray($row['map_of_structs']); + $this->assertIsArray($row['map_of_structs']['key_0']); + $this->assertIsInt($row['map_of_structs']['key_0']['int_field']); + $this->assertIsString($row['map_of_structs']['key_0']['string_field']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } +} diff --git a/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/ParquetIntegrationTestCase.php b/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/ParquetIntegrationTestCase.php new file mode 100644 index 000000000..2ed47be4e --- /dev/null +++ b/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/ParquetIntegrationTestCase.php @@ -0,0 +1,25 @@ +pushHandler(new StreamHandler('php://stdout', Level::Info)); + } else { + $logger = new NullLogger(); + } + + return $logger; + } +} diff --git a/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/SchemaReadingTest.php b/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/SchemaReadingTest.php new file mode 100644 index 000000000..4d144a25e --- /dev/null +++ b/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/SchemaReadingTest.php @@ -0,0 +1,44 @@ +getLogger()); + $this->assertJsonStringEqualsJsonFile( + __DIR__ . '/../Fixtures/lists.json', + \json_encode(($reader->read(__DIR__ . '/../Fixtures/lists.parquet'))->metadata()->schema()->toDDL()) + ); + } + + public function test_reading_maps_schema_ddl() : void + { + $reader = new Reader(logger: $this->getLogger()); + $this->assertJsonStringEqualsJsonFile( + __DIR__ . '/../Fixtures/maps.json', + \json_encode(($reader->read(__DIR__ . '/../Fixtures/maps.parquet'))->metadata()->schema()->toDDL()) + ); + } + + public function test_reading_primitives_schema_ddl() : void + { + $reader = new Reader(logger: $this->getLogger()); + $this->assertJsonStringEqualsJsonFile( + __DIR__ . '/../Fixtures/primitives.json', + \json_encode(($reader->read(__DIR__ . '/../Fixtures/primitives.parquet'))->metadata()->schema()->toDDL()) + ); + } + + public function test_reading_structs_schema_ddl() : void + { + $reader = new Reader(logger: $this->getLogger()); + $this->assertJsonStringEqualsJsonFile( + __DIR__ . '/../Fixtures/structs.json', + \json_encode(($reader->read(__DIR__ . '/../Fixtures/structs.parquet'))->metadata()->schema()->toDDL()) + ); + } +} diff --git a/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/SimpleTypesReadingTest.php b/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/SimpleTypesReadingTest.php new file mode 100644 index 000000000..65e62512e --- /dev/null +++ b/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/SimpleTypesReadingTest.php @@ -0,0 +1,404 @@ +getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('bool')->type()); + $this->assertNull($file->metadata()->schema()->get('bool')->logicalType()); + + $results = \array_merge_recursive(...\iterator_to_array($file->values(['bool'])))['bool']; + $this->assertCount(100, $results); + $this->assertContainsOnly('bool', $results); + $this->assertSame($file->metadata()->rowsNumber(), \count($results)); + } + + public function test_reading_bool_column_with_limit() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('bool')->type()); + $this->assertNull($file->metadata()->schema()->get('bool')->logicalType()); + + $results = \array_merge_recursive(...\iterator_to_array($file->values(['bool'], limit: 50)))['bool']; + $this->assertCount(50, $results); + $this->assertContainsOnly('bool', $results); + } + + public function test_reading_bool_nullable_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('bool_nullable')->type()); + $this->assertNull($file->metadata()->schema()->get('bool_nullable')->logicalType()); + + $results = \array_merge_recursive(...\iterator_to_array($file->values(['bool_nullable'])))['bool_nullable']; + $this->assertCount(100, $results); + $this->assertSame($file->metadata()->rowsNumber(), \count($results)); + $this->assertCount(50, \array_filter($results, fn ($value) => $value === null)); + $this->assertCount(50, \array_filter($results, fn ($value) => $value !== null)); + } + + public function test_reading_bool_nullable_column_with_limit() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('bool_nullable')->type()); + $this->assertNull($file->metadata()->schema()->get('bool_nullable')->logicalType()); + + $results = \array_merge_recursive(...\iterator_to_array($file->values(['bool_nullable'], $limit = 50)))['bool_nullable']; + $this->assertCount($limit, $results); + $this->assertCount($limit / 2, \array_filter($results, fn ($value) => $value === null)); + $this->assertCount($limit / 2, \array_filter($results, fn ($value) => $value !== null)); + } + + public function test_reading_date_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::INT32, $file->metadata()->schema()->get('date')->type()); + $this->assertEquals('DATE', $file->metadata()->schema()->get('date')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['date']) as $row) { + $this->assertInstanceOf(\DateTimeImmutable::class, $row['date']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_date_nullable_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::INT32, $file->metadata()->schema()->get('date_nullable')->type()); + $this->assertEquals('DATE', $file->metadata()->schema()->get('date_nullable')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['date_nullable']) as $rowIndex => $row) { + if ($rowIndex % 2 === 0) { + $this->assertInstanceOf(\DateTimeImmutable::class, $row['date_nullable']); + } else { + $this->assertNull($row['date_nullable']); + } + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_enum_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::BYTE_ARRAY, $file->metadata()->schema()->get('enum')->type()); + $this->assertEquals('STRING', $file->metadata()->schema()->get('enum')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['enum']) as $row) { + $this->assertIsString($row['enum']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_int32_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::INT32, $file->metadata()->schema()->get('int32')->type()); + $this->assertNull($file->metadata()->schema()->get('int32')->logicalType()); + + $count = 0; + + foreach ($file->values(['int32']) as $row) { + $this->assertIsInt($row['int32']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_int32_nullable_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::INT32, $file->metadata()->schema()->get('int32_nullable')->type()); + $this->assertNull($file->metadata()->schema()->get('int32_nullable')->logicalType()); + + $count = 0; + + foreach ($file->values(['int32_nullable']) as $rowIndex => $row) { + if ($rowIndex % 2 === 0) { + $this->assertIsInt($row['int32_nullable']); + } else { + $this->assertNull($row['int32_nullable']); + } + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_int64() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::INT64, $file->metadata()->schema()->get('int64')->type()); + $this->assertNull($file->metadata()->schema()->get('int64')->logicalType()); + + $count = 0; + + foreach ($file->values(['int64']) as $row) { + $this->assertIsInt($row['int64']); + $count++; + } + + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_int64_nullable_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::INT64, $file->metadata()->schema()->get('int64_nullable')->type()); + $this->assertNull($file->metadata()->schema()->get('int64_nullable')->logicalType()); + + $count = 0; + + foreach ($file->values(['int64_nullable']) as $rowIndex => $row) { + if ($rowIndex % 2 === 0) { + $this->assertIsInt($row['int64_nullable']); + } else { + $this->assertNull($row['int64_nullable']); + } + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_json_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::BYTE_ARRAY, $file->metadata()->schema()->get('json')->type()); + $this->assertEquals('STRING', $file->metadata()->schema()->get('json')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['json']) as $row) { + $this->assertIsString($row['json']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_json_nullable_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::BYTE_ARRAY, $file->metadata()->schema()->get('json_nullable')->type()); + $this->assertEquals('STRING', $file->metadata()->schema()->get('json_nullable')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['json_nullable']) as $rowIndex => $row) { + if ($rowIndex % 2 === 0) { + $this->assertIsString($row['json_nullable']); + } else { + $this->assertNull($row['json_nullable']); + } + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_string_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::BYTE_ARRAY, $file->metadata()->schema()->get('string')->type()); + $this->assertEquals('STRING', $file->metadata()->schema()->get('string')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['string']) as $row) { + $this->assertIsString($row['string']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_string_nullable_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::BYTE_ARRAY, $file->metadata()->schema()->get('string_nullable')->type()); + $this->assertEquals('STRING', $file->metadata()->schema()->get('string_nullable')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['string_nullable']) as $rowIndex => $row) { + if ($rowIndex % 2 === 0) { + $this->assertIsString($row['string_nullable']); + } else { + $this->assertNull($row['string_nullable']); + } + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_time_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::INT64, $file->metadata()->schema()->get('time')->type()); + $this->assertEquals('TIME', $file->metadata()->schema()->get('time')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['time']) as $row) { + $this->assertIsInt($row['time']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_time_nullable_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::INT64, $file->metadata()->schema()->get('time_nullable')->type()); + $this->assertEquals('TIME', $file->metadata()->schema()->get('time_nullable')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['time_nullable']) as $rowIndex => $row) { + if ($rowIndex % 2 === 0) { + $this->assertIsInt($row['time_nullable']); + } else { + $this->assertNull($row['time_nullable']); + } + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_timestamp_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::INT64, $file->metadata()->schema()->get('timestamp')->type()); + $this->assertEquals('TIMESTAMP', $file->metadata()->schema()->get('timestamp')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['timestamp']) as $row) { + $this->assertIsInt($row['timestamp']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_timestamp_nullable_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::INT64, $file->metadata()->schema()->get('timestamp_nullable')->type()); + $this->assertEquals('TIMESTAMP', $file->metadata()->schema()->get('timestamp_nullable')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['timestamp_nullable']) as $rowIndex => $row) { + if ($rowIndex % 2 === 0) { + $this->assertIsInt($row['timestamp_nullable']); + } else { + $this->assertNull($row['timestamp_nullable']); + } + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_uuid_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::BYTE_ARRAY, $file->metadata()->schema()->get('uuid')->type()); + $this->assertEquals('STRING', $file->metadata()->schema()->get('uuid')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['uuid']) as $row) { + $this->assertIsString($row['uuid']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_uuid_nullable_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/primitives.parquet'); + + $this->assertEquals(PhysicalType::BYTE_ARRAY, $file->metadata()->schema()->get('uuid_nullable')->type()); + $this->assertEquals('STRING', $file->metadata()->schema()->get('uuid_nullable')->logicalType()->name()); + + $count = 0; + + foreach ($file->values(['uuid_nullable']) as $rowIndex => $row) { + if ($rowIndex % 2 === 0) { + $this->assertIsString($row['uuid_nullable']); + } else { + $this->assertNull($row['uuid_nullable']); + } + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } +} diff --git a/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/StructsReadingTest.php b/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/StructsReadingTest.php new file mode 100644 index 000000000..0108c7dae --- /dev/null +++ b/src/lib/parquet/tests/Flow/Parquet/Tests/Integration/StructsReadingTest.php @@ -0,0 +1,242 @@ +getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/structs.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('struct_deeply_nested')->type()); + $this->assertNull($file->metadata()->schema()->get('struct_deeply_nested')->logicalType()); + + $count = 0; + + foreach ($file->values(['struct_deeply_nested']) as $row) { + $this->assertArrayHasKey('struct_0', $row['struct_deeply_nested']); + $this->assertArrayHasKey('int', $row['struct_deeply_nested']['struct_0']); + $this->assertArrayHasKey('struct_1', $row['struct_deeply_nested']['struct_0']); + $this->assertArrayHasKey('string', $row['struct_deeply_nested']['struct_0']['struct_1']); + $this->assertArrayHasKey('struct_2', $row['struct_deeply_nested']['struct_0']['struct_1']); + $this->assertArrayHasKey('bool', $row['struct_deeply_nested']['struct_0']['struct_1']['struct_2']); + $this->assertArrayHasKey('struct_3', $row['struct_deeply_nested']['struct_0']['struct_1']['struct_2']); + $this->assertArrayHasKey('float', $row['struct_deeply_nested']['struct_0']['struct_1']['struct_2']['struct_3']); + $this->assertArrayHasKey('struct_4', $row['struct_deeply_nested']['struct_0']['struct_1']['struct_2']['struct_3']); + $this->assertArrayHasKey('string', $row['struct_deeply_nested']['struct_0']['struct_1']['struct_2']['struct_3']['struct_4']); + $this->assertArrayHasKey('json', $row['struct_deeply_nested']['struct_0']['struct_1']['struct_2']['struct_3']['struct_4']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_struct_deeply_nested_column_with_limit() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/structs.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('struct_deeply_nested')->type()); + $this->assertNull($file->metadata()->schema()->get('struct_deeply_nested')->logicalType()); + + $count = 0; + + foreach ($file->values(['struct_deeply_nested'], $limit = 50) as $row) { + $this->assertArrayHasKey('struct_0', $row['struct_deeply_nested']); + $this->assertArrayHasKey('int', $row['struct_deeply_nested']['struct_0']); + $this->assertArrayHasKey('struct_1', $row['struct_deeply_nested']['struct_0']); + $this->assertArrayHasKey('string', $row['struct_deeply_nested']['struct_0']['struct_1']); + $this->assertArrayHasKey('struct_2', $row['struct_deeply_nested']['struct_0']['struct_1']); + $this->assertArrayHasKey('bool', $row['struct_deeply_nested']['struct_0']['struct_1']['struct_2']); + $this->assertArrayHasKey('struct_3', $row['struct_deeply_nested']['struct_0']['struct_1']['struct_2']); + $this->assertArrayHasKey('float', $row['struct_deeply_nested']['struct_0']['struct_1']['struct_2']['struct_3']); + $this->assertArrayHasKey('struct_4', $row['struct_deeply_nested']['struct_0']['struct_1']['struct_2']['struct_3']); + $this->assertArrayHasKey('string', $row['struct_deeply_nested']['struct_0']['struct_1']['struct_2']['struct_3']['struct_4']); + $this->assertArrayHasKey('json', $row['struct_deeply_nested']['struct_0']['struct_1']['struct_2']['struct_3']['struct_4']); + $count++; + } + $this->assertSame($limit, $count); + } + + public function test_reading_struct_flat_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/structs.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('struct_flat')->type()); + $this->assertNull($file->metadata()->schema()->get('struct_flat')->logicalType()); + + $count = 0; + + foreach ($file->values(['struct_flat']) as $row) { + $this->assertArrayHasKey('string', $row['struct_flat']); + $this->assertArrayHasKey('int', $row['struct_flat']); + $this->assertArrayHasKey('list_of_ints', $row['struct_flat']); + $this->assertArrayHasKey('map_of_string_int', $row['struct_flat']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_struct_nested_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/structs.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('struct_nested')->type()); + $this->assertNull($file->metadata()->schema()->get('struct_nested')->logicalType()); + + $count = 0; + + foreach ($file->values(['struct_nested']) as $row) { + $this->assertArrayHasKey('string', $row['struct_nested']); + $this->assertArrayHasKey('struct_flat', $row['struct_nested']); + $this->assertArrayHasKey('int', $row['struct_nested']['struct_flat']); + $this->assertArrayHasKey('list_of_ints', $row['struct_nested']['struct_flat']); + $this->assertArrayHasKey('map_of_string_int', $row['struct_nested']['struct_flat']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_struct_nested_with_list_of_lists_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/structs.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('struct_nested_with_list_of_lists')->type()); + $this->assertNull($file->metadata()->schema()->get('struct_nested_with_list_of_lists')->logicalType()); + + $count = 0; + + foreach ($file->values(['struct_nested_with_list_of_lists']) as $row) { + $this->assertArrayHasKey('string', $row['struct_nested_with_list_of_lists']); + $this->assertArrayHasKey('struct', $row['struct_nested_with_list_of_lists']); + $this->assertArrayHasKey('int', $row['struct_nested_with_list_of_lists']['struct']); + $this->assertArrayHasKey('list_of_list_of_ints', $row['struct_nested_with_list_of_lists']['struct']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_struct_nested_with_list_of_maps_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/structs.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('struct_nested_with_list_of_maps')->type()); + $this->assertNull($file->metadata()->schema()->get('struct_nested_with_list_of_maps')->logicalType()); + + $count = 0; + + foreach ($file->values(['struct_nested_with_list_of_maps']) as $row) { + $this->assertArrayHasKey('string', $row['struct_nested_with_list_of_maps']); + $this->assertArrayHasKey('struct', $row['struct_nested_with_list_of_maps']); + $this->assertArrayHasKey('int', $row['struct_nested_with_list_of_maps']['struct']); + $this->assertArrayHasKey('list_of_map_of_string_int', $row['struct_nested_with_list_of_maps']['struct']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_struct_nested_with_map_of_list_of_ints_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/structs.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('struct_nested_with_map_of_list_of_ints')->type()); + $this->assertNull($file->metadata()->schema()->get('struct_nested_with_map_of_list_of_ints')->logicalType()); + + $count = 0; + + foreach ($file->values(['struct_nested_with_map_of_list_of_ints']) as $row) { + $this->assertArrayHasKey('string', $row['struct_nested_with_map_of_list_of_ints']); + $this->assertArrayHasKey('struct', $row['struct_nested_with_map_of_list_of_ints']); + $this->assertArrayHasKey('int', $row['struct_nested_with_map_of_list_of_ints']['struct']); + $this->assertArrayHasKey('map_of_int_list_of_string', $row['struct_nested_with_map_of_list_of_ints']['struct']); + $this->assertIsList($row['struct_nested_with_map_of_list_of_ints']['struct']['map_of_int_list_of_string'][0]); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_struct_nested_with_map_of_string_map_of_string_string_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/structs.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('struct_nested_with_map_of_string_map_of_string_string')->type()); + $this->assertNull($file->metadata()->schema()->get('struct_nested_with_map_of_string_map_of_string_string')->logicalType()); + + $count = 0; + + foreach ($file->values(['struct_nested_with_map_of_string_map_of_string_string']) as $row) { + $this->assertArrayHasKey('string', $row['struct_nested_with_map_of_string_map_of_string_string']); + $this->assertArrayHasKey('struct', $row['struct_nested_with_map_of_string_map_of_string_string']); + $this->assertArrayHasKey('int', $row['struct_nested_with_map_of_string_map_of_string_string']['struct']); + $this->assertArrayHasKey('map_of_string_map_of_string_string', $row['struct_nested_with_map_of_string_map_of_string_string']['struct']); + $this->assertArrayHasKey('outer_key_0', $row['struct_nested_with_map_of_string_map_of_string_string']['struct']['map_of_string_map_of_string_string']); + $this->assertArrayHasKey('inner_key_0', $row['struct_nested_with_map_of_string_map_of_string_string']['struct']['map_of_string_map_of_string_string']['outer_key_0']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } + + public function test_reading_struct_nested_with_map_of_string_map_of_string_string_column_with_limit() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/structs.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('struct_nested_with_map_of_string_map_of_string_string')->type()); + $this->assertNull($file->metadata()->schema()->get('struct_nested_with_map_of_string_map_of_string_string')->logicalType()); + + $count = 0; + + foreach ($file->values(['struct_nested_with_map_of_string_map_of_string_string'], $limit = 50) as $row) { + $this->assertArrayHasKey('string', $row['struct_nested_with_map_of_string_map_of_string_string']); + $this->assertArrayHasKey('struct', $row['struct_nested_with_map_of_string_map_of_string_string']); + $this->assertArrayHasKey('int', $row['struct_nested_with_map_of_string_map_of_string_string']['struct']); + $this->assertArrayHasKey('map_of_string_map_of_string_string', $row['struct_nested_with_map_of_string_map_of_string_string']['struct']); + $this->assertArrayHasKey('outer_key_0', $row['struct_nested_with_map_of_string_map_of_string_string']['struct']['map_of_string_map_of_string_string']); + $this->assertArrayHasKey('inner_key_0', $row['struct_nested_with_map_of_string_map_of_string_string']['struct']['map_of_string_map_of_string_string']['outer_key_0']); + $count++; + } + $this->assertSame($limit, $count); + } + + public function test_reading_struct_with_list_and_map_of_structs_column() : void + { + $reader = new Reader(logger: $this->getLogger()); + $file = $reader->read(__DIR__ . '/../Fixtures/structs.parquet'); + + $this->assertEquals(PhysicalType::BOOLEAN, $file->metadata()->schema()->get('struct_with_list_and_map_of_structs')->type()); + $this->assertNull($file->metadata()->schema()->get('struct_with_list_and_map_of_structs')->logicalType()); + + $count = 0; + + foreach ($file->values(['struct_with_list_and_map_of_structs']) as $row) { + $this->assertArrayHasKey('string', $row['struct_with_list_and_map_of_structs']); + $this->assertArrayHasKey('struct', $row['struct_with_list_and_map_of_structs']); + $this->assertArrayHasKey('int', $row['struct_with_list_and_map_of_structs']['struct']); + $this->assertArrayHasKey('list_of_structs', $row['struct_with_list_and_map_of_structs']['struct']); + $this->assertArrayHasKey('map_of_string_structs', $row['struct_with_list_and_map_of_structs']['struct']); + $this->assertArrayHasKey('key_0', $row['struct_with_list_and_map_of_structs']['struct']['map_of_string_structs']); + $this->assertArrayHasKey('int', $row['struct_with_list_and_map_of_structs']['struct']['map_of_string_structs']['key_0']); + $this->assertArrayHasKey('list', $row['struct_with_list_and_map_of_structs']['struct']['map_of_string_structs']['key_0']); + $this->assertIsList($row['struct_with_list_and_map_of_structs']['struct']['map_of_string_structs']['key_0']['list']); + $count++; + } + $this->assertSame(100, $count); + $this->assertSame($file->metadata()->rowsNumber(), $count); + } +} diff --git a/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/BinaryReader/BinaryBufferReaderTest.php b/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/BinaryReader/BinaryBufferReaderTest.php new file mode 100644 index 000000000..12ab7961d --- /dev/null +++ b/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/BinaryReader/BinaryBufferReaderTest.php @@ -0,0 +1,122 @@ +readDouble(); + $this->assertEqualsWithDelta(42.8640126711, $result, 0.0000000001); + } + + public function test_readFloat() : void + { + $buffer = \pack('C4', 0x42, 0x29, 0xB9, 0x9A); + $reader = new BinaryBufferReader($buffer, ByteOrder::BIG_ENDIAN); + $result = $reader->readFloat(); + $this->assertEqualsWithDelta(42.43125152587, $result, 0.0001); + } + + public function test_readInt32_big_endian() : void + { + $buffer = \pack('C*', 0, 0, 0, 1); // 0x00000001 in big endian + $reader = new BinaryBufferReader($buffer, ByteOrder::BIG_ENDIAN); + + $result = $reader->readInt32(); + $this->assertSame(1, $result); + } + + public function test_readInt32_boundary() : void + { + $buffer = \pack('C*', 255, 255, 255, 255); // 0xFFFFFFFF + $reader = new BinaryBufferReader($buffer, ByteOrder::LITTLE_ENDIAN); + + $result = $reader->readInt32(); + $this->assertSame(4294967295, $result); // PHP treats it as unsigned here + } + + public function test_readInt32_little_endian() : void + { + $buffer = \pack('C*', 1, 0, 0, 0); // 0x00000001 in little endian + $reader = new BinaryBufferReader($buffer, ByteOrder::LITTLE_ENDIAN); + + $result = $reader->readInt32(); + $this->assertSame(1, $result); + } + + public function test_readInt64() : void + { + $buffer = \pack('C*', 1, 0, 0, 0, 0, 0, 0, 0); + $reader = new BinaryBufferReader($buffer, ByteOrder::LITTLE_ENDIAN); + + $result = $reader->readInt64(); + $this->assertSame(1, $result); + } + + public function test_readString_valid_input() : void + { + $stringData = 'Hello, World!'; + $length = \pack('V', \strlen($stringData)); // Assuming little-endian 32-bit length + $buffer = $length . $stringData; + + $reader = new BinaryBufferReader($buffer, ByteOrder::LITTLE_ENDIAN); + + $result = $reader->readString(); + + $this->assertSame($stringData, $result); + } + + public function test_readString_zero_length() : void + { + $length = \pack('V', 0); // 32-bit zero length + $buffer = $length; + + $reader = new BinaryBufferReader($buffer, ByteOrder::LITTLE_ENDIAN); + + $result = $reader->readString(); + + $this->assertSame('', $result); + } + + public function test_readUInt32() : void + { + $buffer = \pack('C*', 1, 0, 0, 0); + $reader = new BinaryBufferReader($buffer, ByteOrder::LITTLE_ENDIAN); + + $result = $reader->readUInt32(); + $this->assertSame(1, $result); + } + + public function test_readUInt64() : void + { + $buffer = \pack('C*', 1, 0, 0, 0, 0, 0, 0, 0); + $reader = new BinaryBufferReader($buffer, ByteOrder::LITTLE_ENDIAN); + + $result = $reader->readUInt64(); + $this->assertSame(1, $result); // This test assumes PHP handles unsigned 64-bit integers + } + + public function test_readVarInt() : void + { + // Using examples: + // 1 is encoded as 00000001 + // 300 is encoded as 10101100 00000010 + $buffer = \pack('C*', 0x01, 0xAC, 0x02); + $reader = new BinaryBufferReader($buffer, ByteOrder::LITTLE_ENDIAN); + + // First varint should be 1 + $result1 = $reader->readVarInt(); + $this->assertSame(1, $result1); + + // Second varint should be 300 + $result2 = $reader->readVarInt(); + $this->assertSame(300, $result2); + } +} diff --git a/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/BinaryReader/BytesTest.php b/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/BinaryReader/BytesTest.php new file mode 100644 index 000000000..1e1f392f5 --- /dev/null +++ b/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/BinaryReader/BytesTest.php @@ -0,0 +1,84 @@ +assertEquals('Hello', $buffer->toString()); + $this->assertEquals(new DataSize(40), $buffer->size()); + } + + public function test_buffer_size() : void + { + $buffer = new Bytes([72, 101, 108, 108, 111]); // ASCII for "Hello" + $this->assertEquals(new DataSize(40), $buffer->size()); // 5 bytes * 8 bits per byte = 40 bits + } + + public function test_buffer_to_string() : void + { + $buffer = new Bytes([72, 101, 108, 108, 111]); // ASCII for "Hello" + $this->assertEquals('Hello', $buffer->toString()); + } + + public function test_empty_buffer_size() : void + { + $buffer = new Bytes([]); + $this->assertEquals(new DataSize(0), $buffer->size()); + } + + public function test_empty_buffer_to_string() : void + { + $buffer = new Bytes([]); + $this->assertEquals('', $buffer->toString()); + } + + public function test_to_int() : void + { + $bytes = new Bytes([1, 0, 0, 0]); // Little-endian representation of the integer 1 + $this->assertEquals(1, $bytes->toInt()); + } + + public function test_to_int_big_endian() : void + { + $bytes = new Bytes([0, 0, 0, 1], ByteOrder::BIG_ENDIAN); + $this->assertEquals(1, $bytes->toInt()); + } + + public function test_to_int_big_endian_multiByte() : void + { + $bytes = new Bytes([1, 0, 0], ByteOrder::BIG_ENDIAN); // Big-endian representation of the integer 65536 + $this->assertEquals(65536, $bytes->toInt()); + } + + public function test_to_int_big_endian_non_zero_bytes() : void + { + $bytes = new Bytes([0xFF, 0xFF], ByteOrder::BIG_ENDIAN); + $this->assertEquals(65535, $bytes->toInt()); + } + + public function test_to_int_empty_bytes() : void + { + $bytes = new Bytes([]); // Should return 0 when bytes array is empty + $this->assertEquals(0, $bytes->toInt()); + } + + public function test_to_int_non_zero_bytes() : void + { + $bytes = new Bytes([0xFF, 0xFF]); // Little-endian representation of the integer 65535 + $this->assertEquals(65535, $bytes->toInt()); + } + + public function test_to_int_single_byte() : void + { + $bytes = new Bytes([42]); // Single byte representing the integer 42 + $this->assertEquals(42, $bytes->toInt()); + } +} diff --git a/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/Data/RLEBitPackedHybridTest.php b/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/Data/RLEBitPackedHybridTest.php new file mode 100644 index 000000000..558a8387c --- /dev/null +++ b/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/Data/RLEBitPackedHybridTest.php @@ -0,0 +1,167 @@ +getMockBuilder(BinaryReader::class) + ->disableOriginalConstructor() + ->getMock(); + + $bitWidth = 8; + $varInt = 2; + $maxItems = 5; + + $binaryReader->expects($this->once()) + ->method('remainingLength') + ->willReturn(new DataSize(1)); + + $binaryReader->expects($this->once()) + ->method('readBytes') + ->willReturn(new Bytes([8])); + + $result = []; + $rleBitPackedHybrid->decodeBitPacked($binaryReader, $bitWidth, $varInt, $maxItems, $result); + + $this->assertEquals([8], $result); + } + + public function test_decodeBitPacked_with_different_bitWidth() : void + { + $rleBitPackedHybrid = new RLEBitPackedHybrid(); + $binaryReader = $this->getMockBuilder(BinaryReader::class) + ->disableOriginalConstructor() + ->getMock(); + + $bitWidth = 4; + $varInt = 2; + $maxItems = 5; + + $binaryReader->expects($this->once()) + ->method('remainingLength') + ->willReturn(new DataSize(2)); + + $binaryReader->expects($this->once()) + ->method('readBytes') + ->willReturn(new Bytes([8, 4])); + + $result = []; + $rleBitPackedHybrid->decodeBitPacked($binaryReader, $bitWidth, $varInt, $maxItems, $result); + + $this->assertEquals([8, 0, 4, 0], $result); + } + + public function test_decodeBitPacked_with_fewer_remainingBytes_than_byteCount() : void + { + $rleBitPackedHybrid = new RLEBitPackedHybrid(); + $binaryReader = $this->getMockBuilder(BinaryReader::class) + ->disableOriginalConstructor() + ->getMock(); + + $bitWidth = 8; + $varInt = 2; + $maxItems = 5; + + $binaryReader->expects($this->once()) + ->method('remainingLength') + ->willReturn(new DataSize(1)); + + $binaryReader->expects($this->once()) + ->method('readBytes') + ->willReturn(new Bytes([8])); + + $result = []; + $rleBitPackedHybrid->decodeBitPacked($binaryReader, $bitWidth, $varInt, $maxItems, $result); + + $this->assertEquals([8], $result); + } + + public function test_decodeBitPacked_with_zero_groupCount_and_count() : void + { + $rleBitPackedHybrid = new RLEBitPackedHybrid(); + $binaryReader = $this->getMockBuilder(BinaryReader::class) + ->disableOriginalConstructor() + ->getMock(); + + $bitWidth = 8; + $varInt = 0; + $maxItems = 5; + + $result = []; + $rleBitPackedHybrid->decodeBitPacked($binaryReader, $bitWidth, $varInt, $maxItems, $result); + + $this->assertEquals([], $result); + } + + public function test_decodeRLE_with_isLiteralRun_false() : void + { + $rleBitPackedHybrid = new RLEBitPackedHybrid(); + $binaryReader = $this->getMockBuilder(BinaryReader::class) + ->disableOriginalConstructor() + ->getMock(); + + $bitWidth = 8; + $intVar = 4; // Even intVar, so isLiteralRun will be false + $maxItems = 2; + + $binaryReader->expects($this->once()) + ->method('readBytes') + ->willReturn(new Bytes([2])); + + $result = []; + $rleBitPackedHybrid->decodeRLE($binaryReader, $bitWidth, $intVar, $maxItems, $result); + + $this->assertEquals([2, 2], $result); + } + + public function test_decodeRLE_with_isLiteralRun_true() : void + { + $rleBitPackedHybrid = new RLEBitPackedHybrid(); + $binaryReader = $this->getMockBuilder(BinaryReader::class) + ->disableOriginalConstructor() + ->getMock(); + + $bitWidth = 8; + $intVar = 3; // Odd intVar, so isLiteralRun will be true + $maxItems = 2; + + $binaryReader->expects($this->exactly(1)) + ->method('readBytes') + ->willReturn(new Bytes([])); + + $binaryReader->expects($this->exactly(1)) + ->method('readBits') + ->willReturnOnConsecutiveCalls([1]); + + $result = []; + $rleBitPackedHybrid->decodeRLE($binaryReader, $bitWidth, $intVar, $maxItems, $result); + + $this->assertEquals([[1]], $result); + } + + public function test_decodeRLE_with_runLength_zero() : void + { + $rleBitPackedHybrid = new RLEBitPackedHybrid(); + $binaryReader = $this->getMockBuilder(BinaryReader::class) + ->disableOriginalConstructor() + ->getMock(); + + $bitWidth = 8; + $intVar = 0; + $maxItems = 5; + + $result = []; + $rleBitPackedHybrid->decodeRLE($binaryReader, $bitWidth, $intVar, $maxItems, $result); + + $this->assertEquals([], $result); + } +} diff --git a/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/FunctionsTest.php b/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/FunctionsTest.php new file mode 100644 index 000000000..baddf86f3 --- /dev/null +++ b/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/FunctionsTest.php @@ -0,0 +1,42 @@ +assertSame( + [ + 'members' => [ + 0 => [ + 'addresses' => [ + 0 => ['street' => 'Street_2_0_0'], + 1 => ['street' => 'Street_2_0_1'], + ], + ], + 1 => [ + 'addresses' => [ + 0 => ['street' => 'Street_2_1_0'], + ], + ], + ], + ], + \Flow\Parquet\array_merge_recursive( + [ + 'members' => [ + 0 => ['addresses' => [0 => ['street' => 'Street_2_0_0']]], + ], + ], + [ + 'members' => [ + 0 => ['addresses' => [1 => ['street' => 'Street_2_0_1']]], + 1 => ['addresses' => [0 => ['street' => 'Street_2_1_0']]], + ], + ] + ) + ); + } +} diff --git a/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/ParquetFile/Page/ColumnDataTest.php b/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/ParquetFile/Page/ColumnDataTest.php new file mode 100644 index 000000000..b2a3568d2 --- /dev/null +++ b/src/lib/parquet/tests/Flow/Parquet/Tests/Unit/ParquetFile/Page/ColumnDataTest.php @@ -0,0 +1,103 @@ +assertEquals( + new ColumnData( + PhysicalType::INT32, + null, + [], + [1, 0, 1, 0, 1, 0, 1, 0, 1, 0], + [0, 2, 4, 6, 8, null, null, null, null, null] + ), + $columnData->splitLastRow()[0] + ); + + $this->assertEquals( + new ColumnData( + PhysicalType::INT32, + null, + [], + [], + [] + ), + $columnData->splitLastRow()[1] + ); + } + + public function test_splitting_last_row() : void + { + $repetitions = [0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1]; + $definitions = [3, 3, 2, 2, 3, 3, 2, 3, 3, 2, 2, 2, 2, 3, 3, 2, 2, 3, 2, 2, 3, 2]; + $values = [10, 7, 9, 8, 9, 4, 6, 3, 10, 8]; + + $columnData = new ColumnData(PhysicalType::INT32, null, $repetitions, $definitions, $values); + + $this->assertEquals( + new ColumnData( + PhysicalType::INT32, + null, + [0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1], + [3, 3, 2, 2, 3, 3, 2, 3, 3, 2, 2, 2, 2, 3, 3, 2, 2, 3, 2, 2], + [10, 7, 9, 8, 9, 4, 6, 3, 10] + ), + $columnData->splitLastRow()[0] + ); + + $this->assertEquals( + new ColumnData( + PhysicalType::INT32, + null, + [0, 1], + [3, 2], + [8] + ), + $columnData->splitLastRow()[1] + ); + } + + public function test_splitting_map_rows() : void + { + $repetitions = [0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0]; + $definitions = [3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3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, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3], + [5, 7, 10, 3, 1, 6, 7, 9, 8, 3, 8, 8, 3, 2, 10, 4, 8, 4, 3, 10, 4, 10, 10, 5, 4, 4, 4, 9, 7, 8, 8, 6, 6, 5, 8, 2, 2, 2, 6, 10, 3, 9, 5, 3, 1, 2, 10, 3, 2, 10, 9, 10, 6, 3, 1, 3, 2, 5, 8, 3, 9, 4, 6, 5, 6, 6, 2, 1, 5, 7, 6, 6, 2, 1, 9, 9, 2, 2, 2, 6, 7, 10, 2, 7, 9, 9, 9, 2, 1, 4, 7, 3, 10, 6, 5, 6, 10, 6, 4, 1, 7, 9, 7, 3, 2, 3, 9, 10, 9, 7, 1, 8, 9, 10, 2, 1, 6, 2, 1, 3, 1, 1, 6, 5, 8, 7, 2, 7, 4, 6, 10, 5, 8, 5, 9, 3, 2, 6, 8, 2, 3, 5, 4, 8, 7, 4, 8, 8, 3, 9] + ), + $columnData->splitLastRow()[0] + ); + + $this->assertEquals( + new ColumnData( + PhysicalType::INT32, + null, + [0], + [0], + [] + ), + $columnData->splitLastRow()[1] + ); + } +}