Coverage Report

Created: 2026-07-07 19:03

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