Coverage Report

Created: 2026-07-07 12:34

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format_v2/parquet/parquet_reader.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "format_v2/parquet/parquet_reader.h"
19
20
#include <algorithm>
21
#include <map>
22
#include <memory>
23
#include <optional>
24
#include <ranges>
25
#include <unordered_set>
26
#include <utility>
27
#include <vector>
28
29
#include "core/assert_cast.h"
30
#include "core/block/block.h"
31
#include "core/data_type/data_type_array.h"
32
#include "core/data_type/data_type_factory.hpp"
33
#include "core/data_type/data_type_map.h"
34
#include "core/data_type/data_type_nullable.h"
35
#include "core/data_type/data_type_struct.h"
36
#include "format_v2/column_mapper.h"
37
#include "format_v2/parquet/parquet_column_schema.h"
38
#include "format_v2/parquet/parquet_file_context.h"
39
#include "format_v2/parquet/parquet_scan.h"
40
#include "format_v2/parquet/parquet_statistics.h"
41
#include "format_v2/parquet/reader/column_reader.h"
42
#include "runtime/runtime_state.h"
43
44
namespace doris::format::parquet {
45
46
struct ParquetReaderScanState {
47
    ParquetFileContext file_context;
48
    std::vector<std::unique_ptr<ParquetColumnSchema>> file_schema;
49
    RowGroupScanPlan scan_plan;
50
    ParquetScanScheduler scheduler;
51
    const RuntimeState* runtime_state = nullptr;
52
    const cctz::time_zone* timezone = nullptr;
53
    bool enable_bloom_filter = false;
54
    bool enable_page_cache = false;
55
    bool enable_strict_mode = false;
56
};
57
58
153
int64_t column_chunk_start_offset(const ::parquet::ColumnChunkMetaData& column_metadata) {
59
153
    return column_metadata.has_dictionary_page()
60
153
                   ? cast_set<int64_t>(column_metadata.dictionary_page_offset())
61
153
                   : cast_set<int64_t>(column_metadata.data_page_offset());
62
153
}
63
64
void collect_all_leaf_column_ids(const ParquetColumnSchema& column_schema,
65
142
                                 std::unordered_set<int>* leaf_column_ids) {
66
142
    DORIS_CHECK(leaf_column_ids != nullptr);
67
142
    if (column_schema.kind == ParquetColumnSchemaKind::PRIMITIVE) {
68
133
        if (column_schema.leaf_column_id >= 0) {
69
133
            leaf_column_ids->insert(column_schema.leaf_column_id);
70
133
        }
71
133
        return;
72
133
    }
73
13
    for (const auto& child : column_schema.children) {
74
13
        DORIS_CHECK(child != nullptr);
75
13
        collect_all_leaf_column_ids(*child, leaf_column_ids);
76
13
    }
77
9
}
78
79
void collect_projected_leaf_column_ids(const ParquetColumnSchema& column_schema,
80
                                       const format::LocalColumnIndex& projection,
81
135
                                       std::unordered_set<int>* leaf_column_ids) {
82
135
    DORIS_CHECK(leaf_column_ids != nullptr);
83
135
    if (projection.project_all_children || projection.children.empty()) {
84
129
        collect_all_leaf_column_ids(column_schema, leaf_column_ids);
85
129
        return;
86
129
    }
87
7
    for (const auto& child_projection : projection.children) {
88
7
        const auto child_it =
89
11
                std::ranges::find_if(column_schema.children, [&](const auto& child_schema) {
90
11
                    return child_schema->local_id == child_projection.local_id();
91
11
                });
92
7
        DORIS_CHECK(child_it != column_schema.children.end());
93
7
        collect_projected_leaf_column_ids(**child_it, child_projection, leaf_column_ids);
94
7
    }
95
6
}
96
97
void collect_request_leaf_column_ids(
98
        const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
99
104
        const format::FileScanRequest& request, std::unordered_set<int>* leaf_column_ids) {
100
104
    DORIS_CHECK(leaf_column_ids != nullptr);
101
153
    auto collect_scan_column = [&](const format::LocalColumnIndex& projection) {
102
153
        const auto local_id = projection.local_id();
103
153
        if (local_id == format::ROW_POSITION_COLUMN_ID ||
104
153
            local_id == format::GLOBAL_ROWID_COLUMN_ID) {
105
25
            return;
106
25
        }
107
128
        DORIS_CHECK(local_id >= 0 && local_id < static_cast<int32_t>(file_schema.size()));
108
128
        DORIS_CHECK(file_schema[local_id] != nullptr);
109
128
        collect_projected_leaf_column_ids(*file_schema[local_id], projection, leaf_column_ids);
110
128
    };
111
104
    for (const auto& column : request.predicate_columns) {
112
48
        collect_scan_column(column);
113
48
    }
114
105
    for (const auto& column : request.non_predicate_columns) {
115
105
        collect_scan_column(column);
116
105
    }
117
104
}
118
119
std::vector<ParquetPageCacheRange> build_page_cache_ranges(
120
        const ::parquet::FileMetaData& metadata,
121
        const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
122
104
        const format::FileScanRequest& request, const RowGroupScanPlan& row_group_plan) {
123
104
    std::unordered_set<int> leaf_column_ids;
124
104
    collect_request_leaf_column_ids(file_schema, request, &leaf_column_ids);
125
104
    std::vector<ParquetPageCacheRange> ranges;
126
104
    ranges.reserve(row_group_plan.row_groups.size() * leaf_column_ids.size());
127
124
    for (const auto& row_group_plan_item : row_group_plan.row_groups) {
128
124
        auto row_group_metadata = metadata.RowGroup(row_group_plan_item.row_group_id);
129
124
        DORIS_CHECK(row_group_metadata != nullptr);
130
153
        for (const auto leaf_column_id : leaf_column_ids) {
131
153
            DORIS_CHECK(leaf_column_id >= 0 && leaf_column_id < row_group_metadata->num_columns());
132
153
            auto column_metadata = row_group_metadata->ColumnChunk(leaf_column_id);
133
153
            DORIS_CHECK(column_metadata != nullptr);
134
153
            const int64_t offset = column_chunk_start_offset(*column_metadata);
135
153
            const int64_t size = column_metadata->total_compressed_size();
136
153
            DORIS_CHECK(offset >= 0);
137
153
            DORIS_CHECK(size >= 0);
138
153
            if (size > 0) {
139
153
                ranges.push_back(ParquetPageCacheRange {.offset = offset, .size = size});
140
153
            }
141
153
        }
142
124
    }
143
104
    return ranges;
144
104
}
145
146
const ParquetColumnSchema& projected_root_schema(
147
        const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
148
3
        const format::LocalColumnIndex& projection) {
149
3
    const auto local_id = projection.local_id();
150
3
    DORIS_CHECK(local_id >= 0 && local_id < static_cast<int32_t>(file_schema.size()));
151
3
    DORIS_CHECK(file_schema[local_id] != nullptr);
152
3
    return *file_schema[local_id];
153
3
}
154
155
int64_t count_loaded_non_null_values(const ParquetColumnSchema& root_schema,
156
                                     const ParquetColumnReader& shape_reader,
157
3
                                     int64_t expected_rows) {
158
3
    const auto& def_levels = shape_reader.nested_definition_levels();
159
3
    const auto& rep_levels = shape_reader.nested_repetition_levels();
160
3
    const int64_t levels_written = shape_reader.nested_levels_written();
161
3
    DORIS_CHECK(levels_written >= expected_rows);
162
3
    if (root_schema.max_repetition_level == 0) {
163
1
        DORIS_CHECK(levels_written == expected_rows);
164
1
        const int16_t non_null_definition_level = root_schema.nullable_definition_level;
165
1
        int64_t count = 0;
166
6
        for (int64_t level_idx = 0; level_idx < levels_written; ++level_idx) {
167
5
            count += def_levels[level_idx] >= non_null_definition_level ? 1 : 0;
168
5
        }
169
1
        return count;
170
1
    }
171
172
    // For repeated encodings, one top-level row starts when the leaf repetition level moves above
173
    // no higher than the top-level container's repeated boundary. Empty MAP/LIST rows have no
174
    // entries but still carry a level slot; they are non-NULL and must be counted by count(col).
175
2
    const int16_t non_null_definition_level =
176
2
            static_cast<int16_t>(root_schema.definition_level - 1);
177
2
    int64_t counted_rows = 0;
178
2
    int64_t non_null_rows = 0;
179
13
    for (int64_t level_idx = 0; level_idx < levels_written && counted_rows < expected_rows;
180
11
         ++level_idx) {
181
11
        if (rep_levels[level_idx] >= root_schema.repetition_level) {
182
1
            continue;
183
1
        }
184
10
        ++counted_rows;
185
10
        non_null_rows += def_levels[level_idx] >= non_null_definition_level ? 1 : 0;
186
10
    }
187
2
    DORIS_CHECK(counted_rows == expected_rows);
188
2
    return non_null_rows;
189
3
}
190
191
0
DataTypePtr nullable_like_original(const DataTypePtr& type, DataTypePtr nested_type) {
192
0
    return type != nullptr && type->is_nullable() ? make_nullable(nested_type) : nested_type;
193
0
}
194
195
1
int timestamp_tz_scale(const ParquetTypeDescriptor& type_descriptor) {
196
1
    switch (type_descriptor.time_unit) {
197
0
    case ParquetTimeUnit::MILLIS:
198
0
        return 3;
199
0
    case ParquetTimeUnit::MICROS:
200
1
    case ParquetTimeUnit::UNKNOWN:
201
1
    default:
202
1
        return 6;
203
1
    }
204
1
}
205
206
1
bool should_map_to_timestamp_tz(const ParquetColumnSchema& column_schema) {
207
1
    const auto& type_descriptor = column_schema.type_descriptor;
208
1
    return type_descriptor.physical_type == ::parquet::Type::INT96 ||
209
1
           (type_descriptor.is_timestamp && type_descriptor.timestamp_is_adjusted_to_utc);
210
1
}
211
212
1
DataTypePtr apply_timestamp_tz_mapping(ParquetColumnSchema* column_schema) {
213
1
    DORIS_CHECK(column_schema != nullptr);
214
1
    if (column_schema->kind == ParquetColumnSchemaKind::PRIMITIVE) {
215
1
        if (should_map_to_timestamp_tz(*column_schema)) {
216
1
            const bool nullable =
217
1
                    column_schema->type != nullptr && column_schema->type->is_nullable();
218
1
            const auto scale = timestamp_tz_scale(column_schema->type_descriptor);
219
1
            column_schema->type = DataTypeFactory::instance().create_data_type(TYPE_TIMESTAMPTZ,
220
1
                                                                               nullable, 0, scale);
221
1
            column_schema->type_descriptor.doris_type = column_schema->type;
222
1
        }
223
1
        return column_schema->type;
224
1
    }
225
226
0
    std::vector<DataTypePtr> child_types;
227
0
    child_types.reserve(column_schema->children.size());
228
0
    for (auto& child : column_schema->children) {
229
0
        child_types.push_back(apply_timestamp_tz_mapping(child.get()));
230
0
    }
231
232
0
    if (column_schema->kind == ParquetColumnSchemaKind::LIST) {
233
0
        DORIS_CHECK(child_types.size() == 1);
234
0
        column_schema->type = nullable_like_original(
235
0
                column_schema->type, std::make_shared<DataTypeArray>(child_types[0]));
236
0
    } else if (column_schema->kind == ParquetColumnSchemaKind::MAP) {
237
0
        DORIS_CHECK(child_types.size() == 2);
238
0
        column_schema->type = nullable_like_original(
239
0
                column_schema->type, std::make_shared<DataTypeMap>(make_nullable(child_types[0]),
240
0
                                                                   make_nullable(child_types[1])));
241
0
    } else if (column_schema->kind == ParquetColumnSchemaKind::STRUCT) {
242
0
        Strings child_names;
243
0
        child_names.reserve(column_schema->children.size());
244
0
        for (const auto& child : column_schema->children) {
245
0
            child_names.push_back(child->name);
246
0
        }
247
0
        column_schema->type = nullable_like_original(
248
0
                column_schema->type, std::make_shared<DataTypeStruct>(child_types, child_names));
249
0
    }
250
0
    return column_schema->type;
251
1
}
252
253
static Status find_projected_minmax_leaf(const ParquetColumnSchema& column_schema,
254
                                         const format::LocalColumnIndex& projection,
255
14
                                         const ParquetColumnSchema** leaf_schema) {
256
14
    DORIS_CHECK(leaf_schema != nullptr);
257
14
    if (projection.project_all_children || projection.children.empty()) {
258
12
        if (column_schema.leaf_column_id < 0) {
259
2
            return Status::NotSupported(
260
2
                    "Parquet aggregate pushdown only supports primitive column {}",
261
2
                    column_schema.name);
262
2
        }
263
10
        if (column_schema.max_repetition_level > 0) {
264
0
            return Status::NotSupported(
265
0
                    "Parquet aggregate pushdown does not support repeated column {}",
266
0
                    column_schema.name);
267
0
        }
268
10
        *leaf_schema = &column_schema;
269
10
        return Status::OK();
270
10
    }
271
2
    if (projection.children.size() != 1) {
272
0
        return Status::NotSupported(
273
0
                "Parquet aggregate pushdown only supports a single nested leaf under column {}",
274
0
                column_schema.name);
275
0
    }
276
2
    const auto& child_projection = projection.children[0];
277
2
    const auto child_schema_it =
278
2
            std::ranges::find_if(column_schema.children, [&](const auto& child_schema) {
279
2
                return child_schema->local_id == child_projection.local_id();
280
2
            });
281
2
    if (child_schema_it != column_schema.children.end()) {
282
2
        return find_projected_minmax_leaf(**child_schema_it, child_projection, leaf_schema);
283
2
    }
284
0
    return Status::InvalidArgument("Invalid parquet aggregate projection local id {} for column {}",
285
0
                                   child_projection.local_id(), column_schema.name);
286
2
}
287
288
void ParquetReader::_fill_column_definition(const ParquetColumnSchema& column_schema,
289
241
                                            format::ColumnDefinition* field) const {
290
241
    if (column_schema.parquet_field_id >= 0) {
291
95
        field->identifier = Field::create_field<TYPE_INT>(column_schema.parquet_field_id);
292
146
    } else {
293
146
        field->identifier = Field::create_field<TYPE_STRING>(column_schema.name);
294
146
    }
295
241
    field->local_id = column_schema.local_id;
296
241
    field->name = column_schema.name;
297
241
    field->type = column_schema.type != nullptr && !column_schema.type->is_nullable()
298
241
                          ? make_nullable(column_schema.type)
299
241
                          : column_schema.type;
300
241
    field->children.clear();
301
241
    field->children.reserve(column_schema.children.size());
302
241
    for (const auto& child : column_schema.children) {
303
26
        format::ColumnDefinition child_field;
304
26
        _fill_column_definition(*child, &child_field);
305
26
        field->children.push_back(std::move(child_field));
306
26
    }
307
241
}
308
309
ParquetReader::ParquetReader(std::shared_ptr<io::FileSystemProperties>& system_properties,
310
                             std::unique_ptr<io::FileDescription>& file_description,
311
                             std::shared_ptr<io::IOContext> io_ctx, RuntimeProfile* profile,
312
                             std::optional<format::GlobalRowIdContext> global_rowid_context,
313
                             bool enable_mapping_timestamp_tz)
314
109
        : FileReader(system_properties, file_description, io_ctx, profile),
315
109
          _global_rowid_context(global_rowid_context),
316
109
          _enable_mapping_timestamp_tz(enable_mapping_timestamp_tz) {}
317
318
109
ParquetReader::~ParquetReader() = default;
319
320
108
Status ParquetReader::init(RuntimeState* state) {
321
108
    RETURN_IF_ERROR(format::FileReader::init(state));
322
108
    if (_profile != nullptr) {
323
28
        COUNTER_UPDATE(_parquet_profile.file_reader_create_time,
324
28
                       _reader_statistics.file_reader_create_time);
325
28
        COUNTER_UPDATE(_parquet_profile.open_file_num, _reader_statistics.open_file_num);
326
28
    }
327
108
    _state = std::make_unique<ParquetReaderScanState>();
328
108
    _state->enable_bloom_filter =
329
108
            state != nullptr && state->query_options().enable_parquet_filter_by_bloom_filter;
330
108
    _state->enable_page_cache =
331
108
            state != nullptr && state->query_options().enable_parquet_file_page_cache;
332
108
    if (state != nullptr) {
333
108
        _state->runtime_state = state;
334
108
        _state->timezone = &state->timezone_obj();
335
108
        _state->enable_strict_mode = state->enable_strict_mode();
336
108
        _state->scheduler.set_timezone(&state->timezone_obj());
337
108
        _state->scheduler.set_enable_strict_mode(_state->enable_strict_mode);
338
108
    }
339
108
    int64_t merge_read_slice_size = -1;
340
108
    if (state != nullptr && state->query_options().__isset.merge_read_slice_size) {
341
108
        merge_read_slice_size = state->query_options().merge_read_slice_size;
342
108
    }
343
108
    _state->scheduler.set_merge_read_options(_profile, merge_read_slice_size);
344
108
    _state->scheduler.set_batch_size(_batch_size);
345
    // Open parquet file and parse metadata to get file schema.
346
108
    RETURN_IF_ERROR(_state->file_context.open(_tracing_file_reader, _io_ctx.get(),
347
108
                                              _state->enable_page_cache, *_file_description));
348
    // Build file schema from parquet metadata.
349
    // A file reader may expose raw file identifiers, such as Parquet field_id, through ColumnDefinition::identifier
350
108
    RETURN_IF_ERROR(
351
108
            build_parquet_column_schema(*_state->file_context.schema, &_state->file_schema));
352
108
    if (_enable_mapping_timestamp_tz) {
353
1
        for (auto& column_schema : _state->file_schema) {
354
1
            apply_timestamp_tz_mapping(column_schema.get());
355
1
        }
356
1
    }
357
108
    return Status::OK();
358
108
}
359
360
1
void ParquetReader::set_batch_size(size_t batch_size) {
361
1
    _batch_size = std::max<size_t>(1, batch_size);
362
1
    if (_state != nullptr) {
363
0
        _state->scheduler.set_batch_size(_batch_size);
364
0
    }
365
1
}
366
367
98
Status ParquetReader::get_schema(std::vector<format::ColumnDefinition>* file_schema) const {
368
98
    if (file_schema == nullptr) {
369
0
        return Status::InvalidArgument("file_schema is null");
370
0
    }
371
98
    file_schema->clear();
372
98
    if (_state == nullptr || _state->file_context.schema == nullptr) {
373
0
        return Status::Uninitialized("ParquetReader is not open");
374
0
    }
375
376
98
    file_schema->reserve(_state->file_schema.size());
377
313
    for (size_t column_idx = 0; column_idx < _state->file_schema.size(); ++column_idx) {
378
215
        format::ColumnDefinition field;
379
215
        _fill_column_definition(*_state->file_schema[column_idx], &field);
380
215
        DORIS_CHECK(field.local_id == static_cast<int32_t>(column_idx));
381
215
        file_schema->push_back(std::move(field));
382
215
    }
383
98
    if (_global_rowid_context.has_value()) {
384
2
        file_schema->push_back(format::global_rowid_column_definition());
385
2
    }
386
98
    return Status::OK();
387
98
}
388
389
std::unique_ptr<format::TableColumnMapper> ParquetReader::create_column_mapper(
390
58
        format::TableColumnMapperOptions options) const {
391
58
    return std::make_unique<format::ParquetColumnMapper>(std::move(options));
392
58
}
393
394
104
Status ParquetReader::open(std::shared_ptr<format::FileScanRequest> request) {
395
104
    if (_state == nullptr || _state->file_context.metadata == nullptr ||
396
104
        _state->file_context.schema == nullptr) {
397
0
        return Status::Uninitialized("ParquetReader is not open");
398
0
    }
399
104
    auto request_snapshot = request;
400
104
    DORIS_CHECK(request_snapshot != nullptr);
401
104
    RETURN_IF_ERROR(format::FileReader::open(std::move(request)));
402
403
    // `local_positions.empty()` means all columns are needed by table reader
404
    // TODO(gabriel): It will happen only for TVF `select *` query.
405
104
    if (request_snapshot->local_positions.empty()) {
406
29
        for (const auto& col : request_snapshot->predicate_columns) {
407
9
            request_snapshot->local_positions.emplace(col.column_id(),
408
9
                                                      format::LocalIndex(col.column_id().value()));
409
9
        }
410
29
        for (const auto& col : request_snapshot->non_predicate_columns) {
411
17
            request_snapshot->local_positions.emplace(col.column_id(),
412
17
                                                      format::LocalIndex(col.column_id().value()));
413
17
        }
414
29
    }
415
416
104
    const auto num_fields = static_cast<int32_t>(_state->file_schema.size());
417
104
    for (const auto& col : request_snapshot->predicate_columns) {
418
48
        DORIS_CHECK(request_snapshot->local_positions.count(col.column_id()) > 0);
419
48
        const auto local_id = col.local_id();
420
48
        if (local_id == format::ROW_POSITION_COLUMN_ID ||
421
48
            local_id == format::GLOBAL_ROWID_COLUMN_ID) {
422
11
            continue;
423
11
        }
424
37
        DORIS_CHECK(local_id >= 0 && local_id < num_fields);
425
37
    }
426
105
    for (const auto& col : request_snapshot->non_predicate_columns) {
427
105
        DORIS_CHECK(request_snapshot->local_positions.count(col.column_id()) > 0);
428
105
        const auto local_id = col.local_id();
429
105
        if (local_id == format::ROW_POSITION_COLUMN_ID ||
430
105
            local_id == format::GLOBAL_ROWID_COLUMN_ID) {
431
14
            continue;
432
14
        }
433
91
        DORIS_CHECK(local_id >= 0 && local_id < num_fields);
434
91
    }
435
436
104
    RowGroupScanPlan row_group_plan;
437
104
    ParquetScanRange scan_range;
438
104
    scan_range.start_offset = _file_description->range_start_offset;
439
104
    scan_range.size = _file_description->range_size;
440
104
    scan_range.file_size = _file_description->file_size;
441
    // Get selected ranges in row groups according to metadata (Row-Group level index and Page Index including Zonemap, Dictionary, Bloom Filter).
442
104
    RETURN_IF_ERROR(plan_parquet_row_groups(
443
104
            *_state->file_context.metadata, _state->file_context.file_reader.get(),
444
104
            _state->file_schema, *request_snapshot, scan_range, _state->enable_bloom_filter,
445
104
            &row_group_plan, _state->timezone, _state->runtime_state));
446
104
    if (_profile != nullptr) {
447
28
        _parquet_profile.update_pruning_stats(row_group_plan.pruning_stats);
448
28
    }
449
104
    if (_state->enable_page_cache) {
450
104
        _state->file_context.register_page_cache_ranges(
451
104
                build_page_cache_ranges(*_state->file_context.metadata, _state->file_schema,
452
104
                                        *request_snapshot, row_group_plan));
453
104
    }
454
104
    _state->scan_plan = row_group_plan;
455
104
    _state->scheduler.set_page_skip_profile(_parquet_profile.page_skip_profile());
456
104
    _state->scheduler.set_global_rowid_context(_global_rowid_context);
457
104
    _state->scheduler.set_scan_profile(_parquet_profile.scan_profile());
458
104
    _state->scheduler.set_plan(std::move(row_group_plan));
459
104
    _eof = _state->scheduler.empty();
460
104
    return Status::OK();
461
104
}
462
463
142
Status ParquetReader::get_block(Block* file_block, size_t* rows, bool* eof) {
464
142
    if (_state == nullptr || _state->file_context.file_reader == nullptr ||
465
142
        _state->file_context.schema == nullptr) {
466
0
        return Status::Uninitialized("ParquetReader is not open");
467
0
    }
468
142
    *rows = 0;
469
142
    if (_eof) {
470
2
        *eof = true;
471
2
        return Status::OK();
472
2
    }
473
140
    auto request_snapshot = _request;
474
140
    if (request_snapshot == nullptr) {
475
0
        return Status::Cancelled("ParquetReader is closed");
476
0
    }
477
478
140
    const auto predicate_filtered_rows_before = _state->scheduler.predicate_filtered_rows();
479
140
    RETURN_IF_ERROR(_state->scheduler.read_next_batch(_state->file_context, _state->file_schema,
480
140
                                                      *request_snapshot, file_block, rows, eof));
481
140
    _sync_page_cache_profile();
482
140
    if (_io_ctx != nullptr) {
483
36
        _io_ctx->predicate_filtered_rows +=
484
36
                _state->scheduler.predicate_filtered_rows() - predicate_filtered_rows_before;
485
36
    }
486
140
    _eof = *eof;
487
140
    return Status::OK();
488
140
}
489
490
205
void ParquetReader::_sync_page_cache_profile() {
491
205
    if (_profile == nullptr || _state == nullptr) {
492
141
        return;
493
141
    }
494
64
    const auto stats = _state->file_context.page_cache_stats();
495
64
    COUNTER_UPDATE(_parquet_profile.page_read_counter,
496
64
                   stats.read_count - _reported_page_cache_stats.read_count);
497
64
    COUNTER_UPDATE(_parquet_profile.page_cache_write_counter,
498
64
                   stats.write_count - _reported_page_cache_stats.write_count);
499
64
    COUNTER_UPDATE(
500
64
            _parquet_profile.page_cache_compressed_write_counter,
501
64
            stats.compressed_write_count - _reported_page_cache_stats.compressed_write_count);
502
64
    COUNTER_UPDATE(_parquet_profile.page_cache_hit_counter,
503
64
                   stats.hit_count - _reported_page_cache_stats.hit_count);
504
64
    COUNTER_UPDATE(_parquet_profile.page_cache_missing_counter,
505
64
                   stats.miss_count - _reported_page_cache_stats.miss_count);
506
64
    COUNTER_UPDATE(_parquet_profile.page_cache_compressed_hit_counter,
507
64
                   stats.compressed_hit_count - _reported_page_cache_stats.compressed_hit_count);
508
64
    _reported_page_cache_stats = stats;
509
64
}
510
511
2
void ParquetReader::set_condition_cache_context(std::shared_ptr<ConditionCacheContext> ctx) {
512
2
    if (_state == nullptr) {
513
0
        return;
514
0
    }
515
2
    _state->scheduler.set_condition_cache_context(std::move(ctx));
516
2
    if (_io_ctx != nullptr) {
517
        // Condition-cache HIT filters row ranges before batch reading, so skipped rows never belong
518
        // to a later get_block() batch. Report the plan-level skipped rows at the same point where
519
        // the scan plan is rewritten.
520
1
        _io_ctx->condition_cache_filtered_rows += _state->scheduler.condition_cache_filtered_rows();
521
1
    }
522
2
}
523
524
0
int64_t ParquetReader::get_total_rows() const {
525
0
    if (_state == nullptr) {
526
0
        return 0;
527
0
    }
528
0
    int64_t rows = 0;
529
0
    for (const auto& row_group_plan : _state->scan_plan.row_groups) {
530
0
        rows += row_group_plan.row_group_rows;
531
0
    }
532
0
    return rows;
533
0
}
534
535
Status ParquetReader::get_aggregate_result(const format::FileAggregateRequest& request,
536
19
                                           format::FileAggregateResult* result) {
537
19
    DORIS_CHECK(result != nullptr);
538
19
    if (_state == nullptr || _state->file_context.metadata == nullptr ||
539
19
        _state->file_context.schema == nullptr) {
540
0
        return Status::Uninitialized("ParquetReader is not open");
541
0
    }
542
19
    result->count = 0;
543
19
    result->columns.clear();
544
19
    if (request.agg_type != TPushAggOp::type::COUNT &&
545
19
        request.agg_type != TPushAggOp::type::MINMAX) {
546
1
        return Status::NotSupported("Unsupported parquet aggregate pushdown type {}",
547
1
                                    request.agg_type);
548
1
    }
549
550
    // Aggregate row count in all selected row groups. For MIN/MAX aggregate, this is used to determine whether there is no row group selected.
551
33
    for (const auto& row_group_plan : _state->scan_plan.row_groups) {
552
33
        auto row_group_metadata =
553
33
                _state->file_context.metadata->RowGroup(row_group_plan.row_group_id);
554
33
        DORIS_CHECK(row_group_metadata != nullptr);
555
33
        result->count += row_group_metadata->num_rows();
556
33
    }
557
18
    if (request.agg_type == TPushAggOp::type::COUNT) {
558
7
        if (request.columns.empty()) {
559
4
            return Status::OK();
560
4
        }
561
3
        if (request.columns.size() != 1) {
562
0
            return Status::NotSupported("Parquet COUNT pushdown only supports one count column");
563
0
        }
564
3
        const auto& count_projection = request.columns[0].projection;
565
3
        const auto& root_schema = projected_root_schema(_state->file_schema, count_projection);
566
3
        result->count = 0;
567
3
        for (const auto& row_group_plan : _state->scan_plan.row_groups) {
568
3
            std::shared_ptr<::parquet::RowGroupReader> row_group;
569
3
            try {
570
3
                row_group = _state->file_context.file_reader->RowGroup(row_group_plan.row_group_id);
571
3
            } catch (const ::parquet::ParquetException& e) {
572
0
                return Status::Corruption("Failed to open parquet row group {}: {}",
573
0
                                          row_group_plan.row_group_id, e.what());
574
0
            } catch (const std::exception& e) {
575
0
                return Status::InternalError("Failed to open parquet row group {}: {}",
576
0
                                             row_group_plan.row_group_id, e.what());
577
0
            }
578
579
3
            ParquetColumnReaderFactory column_reader_factory(
580
3
                    row_group, _state->file_context.schema->num_columns(),
581
3
                    &row_group_plan.page_skip_plans, _parquet_profile.page_skip_profile(),
582
3
                    _state->timezone, _state->enable_strict_mode,
583
3
                    _parquet_profile.scan_profile().column_reader_profile);
584
3
            std::unique_ptr<ParquetColumnReader> shape_reader;
585
3
            RETURN_IF_ERROR(column_reader_factory.create_count_shape_reader(
586
3
                    root_schema, &count_projection, &shape_reader));
587
3
            DORIS_CHECK(shape_reader != nullptr);
588
589
3
            int64_t row_group_cursor = 0;
590
3
            for (const auto& selected_range : row_group_plan.selected_ranges) {
591
3
                DORIS_CHECK(selected_range.start >= row_group_cursor);
592
3
                RETURN_IF_ERROR(shape_reader->skip(selected_range.start - row_group_cursor));
593
3
                row_group_cursor = selected_range.start;
594
595
3
                int64_t range_rows_read = 0;
596
6
                while (range_rows_read < selected_range.length) {
597
3
                    const int64_t batch_rows =
598
3
                            std::min<int64_t>(_batch_size, selected_range.length - range_rows_read);
599
                    // COUNT(col) only needs the top-level NULL state. The shape reader loads
600
                    // def/rep levels from one representative leaf and does not build value_indices
601
                    // or values_column. MAP chooses the key leaf; ARRAY/STRUCT may choose a string
602
                    // leaf, but the levels-only protocol still avoids Doris-side string
603
                    // materialization for that leaf.
604
3
                    RETURN_IF_ERROR(shape_reader->load_nested_levels_batch(batch_rows));
605
3
                    result->count +=
606
3
                            count_loaded_non_null_values(root_schema, *shape_reader, batch_rows);
607
3
                    range_rows_read += batch_rows;
608
3
                    row_group_cursor += batch_rows;
609
3
                }
610
3
            }
611
3
        }
612
3
        return Status::OK();
613
3
    }
614
615
11
    result->columns.resize(request.columns.size());
616
20
    for (size_t request_column_idx = 0; request_column_idx < request.columns.size();
617
13
         ++request_column_idx) {
618
13
        const auto file_column_id = request.columns[request_column_idx].projection.local_id();
619
13
        if (file_column_id < 0 ||
620
13
            file_column_id >= static_cast<int32_t>(_state->file_schema.size())) {
621
1
            return Status::InvalidArgument("Invalid parquet aggregate column id {}",
622
1
                                           file_column_id);
623
1
        }
624
12
        const auto& column_schema = _state->file_schema[file_column_id];
625
12
        DORIS_CHECK(column_schema != nullptr);
626
12
        const ParquetColumnSchema* leaf_schema = nullptr;
627
12
        RETURN_IF_ERROR(find_projected_minmax_leaf(
628
12
                *column_schema, request.columns[request_column_idx].projection, &leaf_schema));
629
10
        DORIS_CHECK(leaf_schema != nullptr);
630
631
10
        auto& aggregate_column = result->columns[request_column_idx];
632
10
        aggregate_column.projection = request.columns[request_column_idx].projection;
633
19
        for (const auto& row_group_plan : _state->scan_plan.row_groups) {
634
19
            auto row_group_metadata =
635
19
                    _state->file_context.metadata->RowGroup(row_group_plan.row_group_id);
636
19
            DORIS_CHECK(row_group_metadata != nullptr);
637
19
            auto column_chunk = row_group_metadata->ColumnChunk(leaf_schema->leaf_column_id);
638
19
            DORIS_CHECK(column_chunk != nullptr);
639
19
            const auto statistics = ParquetStatisticsUtils::TransformColumnStatistics(
640
19
                    *leaf_schema, column_chunk->statistics(), _state->timezone);
641
19
            if (!statistics.has_min_max) {
642
1
                return Status::NotSupported("Missing parquet min/max statistics for column {}",
643
1
                                            leaf_schema->name);
644
1
            }
645
18
            if (!aggregate_column.has_min || statistics.min_value < aggregate_column.min_value) {
646
9
                aggregate_column.min_value = statistics.min_value;
647
9
                aggregate_column.has_min = true;
648
9
            }
649
18
            if (!aggregate_column.has_max || aggregate_column.max_value < statistics.max_value) {
650
18
                aggregate_column.max_value = statistics.max_value;
651
18
                aggregate_column.has_max = true;
652
18
            }
653
18
        }
654
9
        if (!aggregate_column.has_min || !aggregate_column.has_max) {
655
0
            return Status::NotSupported("No parquet row group selected for min/max pushdown");
656
0
        }
657
9
    }
658
7
    return Status::OK();
659
11
}
660
661
65
Status ParquetReader::close() {
662
65
    if (_state != nullptr) {
663
65
        _sync_page_cache_profile();
664
65
        RETURN_IF_ERROR(_state->file_context.close());
665
65
    }
666
65
    return FileReader::close();
667
65
}
668
669
108
void ParquetReader::_init_profile() {
670
108
    _parquet_profile.init(_profile);
671
108
}
672
673
} // namespace doris::format::parquet