taiyang-li commented on code in PR #4634:
URL: https://github.com/apache/incubator-gluten/pull/4634#discussion_r1519143018


##########
cpp-ch/local-engine/Storages/Parquet/VectorizedParquetRecordReader.cpp:
##########
@@ -0,0 +1,523 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "VectorizedParquetRecordReader.h"
+
+#if USE_PARQUET
+#include <numeric>
+#include <optional>
+#include <Processors/Chunk.h>
+#include <Processors/Formats/Impl/ArrowBufferedStreams.h>
+#include <Processors/Formats/Impl/ArrowFieldIndexUtil.h>
+#include <Storages/Parquet/ArrowUtils.h>
+#include <arrow/io/memory.h>
+#include <arrow/util/int_util_overflow.h>
+#include <boost/iterator/counting_iterator.hpp>
+#include <parquet/column_reader.h>
+#include <parquet/file_reader.h>
+#include <parquet/page_index.h>
+
+namespace
+{
+bool extend(arrow::io::ReadRange & read_range, const int64_t offset, const 
int64_t length)
+{
+    if (read_range.offset + read_range.length == offset)
+    {
+        read_range.length += length;
+        return true;
+    }
+    return false;
+}
+void emplaceReadRange(local_engine::ReadRanges & read_ranges, const int64_t 
offset, const int64_t length)
+{
+    if (read_ranges.empty() || !extend(read_ranges.back(), offset, length))
+        read_ranges.emplace_back(arrow::io::ReadRange{offset, length});
+}
+
+/// Compute the section of the file that should be read for the given
+/// row group and column chunk.
+::arrow::io::ReadRange ComputeColumnChunkRange(
+    const parquet::FileMetaData & file_metadata, const 
parquet::ColumnChunkMetaData & column_metadata, const int64_t source_size)
+{
+    // For PARQUET-816
+    static constexpr int64_t kMaxDictHeaderSize = 100;
+
+    int64_t col_start = column_metadata.data_page_offset();
+    if (column_metadata.has_dictionary_page() && 
column_metadata.dictionary_page_offset() > 0
+        && col_start > column_metadata.dictionary_page_offset())
+        col_start = column_metadata.dictionary_page_offset();
+
+    int64_t col_length = column_metadata.total_compressed_size();
+    int64_t col_end;
+    if (col_start < 0 || col_length < 0)
+        throw parquet::ParquetException("Invalid column metadata (corrupt 
file?)");
+
+    if (arrow::internal::AddWithOverflow(col_start, col_length, &col_end) || 
col_end > source_size)
+        throw parquet::ParquetException("Invalid column metadata (corrupt 
file?)");
+
+    // PARQUET-816 workaround for old files created by older parquet-mr
+    const parquet::ApplicationVersion & version = 
file_metadata.writer_version();
+    if 
(version.VersionLt(parquet::ApplicationVersion::PARQUET_816_FIXED_VERSION()))
+    {
+        // The Parquet MR writer had a bug in 1.2.8 and below where it didn't 
include the
+        // dictionary page header size in total_compressed_size and 
total_uncompressed_size
+        // (see IMPALA-694). We add padding to compensate.
+        const int64_t bytes_remaining = source_size - col_end;
+        const int64_t padding = std::min<int64_t>(kMaxDictHeaderSize, 
bytes_remaining);
+        col_length += padding;
+    }
+    return {col_start, col_length};
+}
+
+std::string lower_column_name_if_need(const std::string & column_name, const 
DB::FormatSettings & settings)
+{
+    std::string result = column_name;
+    if (settings.parquet.case_insensitive_column_matching)
+        boost::to_lower(result);
+    return result;
+}
+}
+
+namespace local_engine
+{
+VectorizedColumnReader::VectorizedColumnReader(
+    const parquet::arrow::SchemaField & field, ParquetFileReaderExt * reader, 
const std::vector<int32_t> & row_groups)
+    : arrowField_(field.field)
+    , input_(field.column_index, reader, row_groups)
+    , record_reader_(parquet::internal::RecordReader::Make(
+          input_.descr(), computeLevelInfo(input_.descr()), 
default_arrow_pool(), arrowField_->type()->id() == ::arrow::Type::DICTIONARY))
+{
+    nextRowGroup();
+}
+
+void VectorizedColumnReader::nextRowGroup()
+{
+    input_.nextChunkWithRowRange().and_then(
+        [&](ColumnChunkPageRead && read) -> std::optional<int64_t>
+        {
+            setPageReader(std::move(read.first), read.second);
+            return std::nullopt;
+        });
+}
+
+void 
VectorizedColumnReader::setPageReader(std::unique_ptr<parquet::PageReader> 
reader, const ReadSequence & read_sequence)
+{
+    if (read_state_)
+    {
+        read_state_->hasLastSkip().and_then(
+            [&](const int64_t skip) -> std::optional<int64_t>
+            {
+                assert(skip < 0);
+                record_reader_->SkipRecords(-skip);
+                return std::nullopt;
+            });
+    }
+    record_reader_->SetPageReader(std::move(reader));
+    read_state_ = std::make_unique<ParquetReadState>(read_sequence);
+}
+
+std::shared_ptr<arrow::ChunkedArray> VectorizedColumnReader::readBatch(int64_t 
batch_size)
+{
+    record_reader_->Reset();
+    record_reader_->Reserve(batch_size);
+
+    while (read_state_->hasMoreRead() && batch_size > 0)
+    {
+        const int64_t readNumber = read_state_->currentRead();
+        if (readNumber < 0)
+        {
+            const int64_t records_skipped = 
record_reader_->SkipRecords(-readNumber);
+            assert(records_skipped == -readNumber);
+            read_state_->skip(records_skipped);
+            assert(hasMoreRead());
+        }
+        else
+        {
+            const int64_t readBatch = std::min(batch_size, readNumber);
+            const int64_t records_read = 
record_reader_->ReadRecords(readBatch);
+            assert(records_read == readBatch);
+            batch_size -= records_read;
+            read_state_->read(records_read);
+            if (!read_state_->hasMoreRead())
+                nextRowGroup();
+        }
+    }
+
+    std::shared_ptr<arrow::ChunkedArray> result;
+    THROW_ARROW_NOT_OK(
+        parquet::arrow::TransferColumnData(record_reader_.get(), arrowField_, 
input_.descr(), local_engine::default_arrow_pool(), &result));
+    return result;
+}
+
+VectorizedParquetRecordReader::VectorizedParquetRecordReader(const DB::Block & 
header, const DB::FormatSettings & format_settings)
+    : format_settings_(format_settings)
+    , arrowColumnToCHColumn_(
+          header,
+          "Parquet",
+          format_settings.parquet.allow_missing_columns,
+          format_settings.null_as_default,
+          format_settings.date_time_overflow_behavior,
+          format_settings.parquet.case_insensitive_column_matching)
+{
+}
+
+bool VectorizedParquetRecordReader::initialize(
+    const DB::Block & header,
+    const std::shared_ptr<arrow::io::RandomAccessFile> & arrow_file,
+    const std::shared_ptr<ColumnIndexFilter> & column_index_filter,
+    const std::shared_ptr<parquet::FileMetaData> & metadata)
+{
+    auto file_reader = parquet::ParquetFileReader::Open(arrow_file, 
parquet::default_reader_properties(), metadata);
+    const parquet::ArrowReaderProperties properties;
+    const parquet::FileMetaData & file_metadata = *(file_reader->metadata());
+    const parquet::SchemaDescriptor * parquet_schema = file_metadata.schema();
+    const auto keyValueMetadata = file_metadata.key_value_metadata();
+    parquet::arrow::SchemaManifest manifest;
+    THROW_ARROW_NOT_OK(parquet::arrow::SchemaManifest::Make(parquet_schema, 
keyValueMetadata, properties, &manifest));
+    std::vector<std::shared_ptr<arrow::Field>> fields;
+    fields.reserve(manifest.schema_fields.size());
+    for (auto const & schema_field : manifest.schema_fields)
+        fields.emplace_back(schema_field.field);
+    const arrow::Schema schema(fields, keyValueMetadata);
+
+    /// column pruning
+    DB::ArrowFieldIndexUtil field_util(

Review Comment:
   Make sure subcolumn pruning in tuple column works 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to