Coverage Report

Created: 2026-09-30 08:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format/parquet/vparquet_group_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/parquet/vparquet_group_reader.h"
19
20
#include <gen_cpp/Exprs_types.h>
21
#include <gen_cpp/Opcodes_types.h>
22
#include <gen_cpp/Types_types.h>
23
#include <gen_cpp/parquet_types.h>
24
#include <string.h>
25
26
#include <algorithm>
27
#include <boost/iterator/iterator_facade.hpp>
28
#include <memory>
29
#include <numeric>
30
#include <ostream>
31
32
#include "common/check.h"
33
#include "common/config.h"
34
#include "common/logging.h"
35
#include "common/object_pool.h"
36
#include "common/status.h"
37
#include "core/assert_cast.h"
38
#include "core/block/block.h"
39
#include "core/block/column_with_type_and_name.h"
40
#include "core/column/column.h"
41
#include "core/column/column_const.h"
42
#include "core/column/column_nullable.h"
43
#include "core/column/column_string.h"
44
#include "core/column/column_vector.h"
45
#include "core/custom_allocator.h"
46
#include "core/data_type/data_type.h"
47
#include "core/data_type/data_type_string.h"
48
#include "core/data_type/define_primitive_type.h"
49
#include "core/pod_array.h"
50
#include "core/types.h"
51
#include "exprs/create_predicate_function.h"
52
#include "exprs/hybrid_set.h"
53
#include "exprs/vdirect_in_predicate.h"
54
#include "exprs/vectorized_fn_call.h"
55
#include "exprs/vexpr.h"
56
#include "exprs/vexpr_context.h"
57
#include "exprs/vliteral.h"
58
#include "exprs/vslot_ref.h"
59
#include "format/parquet/schema_desc.h"
60
#include "format/parquet/vparquet_column_reader.h"
61
#include "format/table/iceberg_reader.h"
62
#include "runtime/descriptors.h"
63
#include "runtime/runtime_state.h"
64
#include "runtime/thread_context.h"
65
#include "storage/segment/column_reader.h"
66
67
namespace cctz {
68
class time_zone;
69
} // namespace cctz
70
namespace doris {
71
class RuntimeState;
72
73
namespace io {
74
struct IOContext;
75
} // namespace io
76
} // namespace doris
77
78
namespace doris {
79
80
const std::vector<int64_t> RowGroupReader::NO_DELETE = {};
81
static constexpr uint32_t MAX_DICT_CODE_PREDICATE_TO_REWRITE = std::numeric_limits<uint32_t>::max();
82
83
RowGroupReader::RowGroupReader(io::FileReaderSPtr file_reader,
84
                               const std::vector<std::string>& read_columns,
85
                               const int32_t row_group_id, const tparquet::RowGroup& row_group,
86
                               const cctz::time_zone* ctz, io::IOContext* io_ctx,
87
                               const PositionDeleteContext& position_delete_ctx,
88
                               const LazyReadContext& lazy_read_ctx, RuntimeState* state,
89
                               const std::set<uint64_t>& column_ids,
90
                               const std::set<uint64_t>& filter_column_ids)
91
75
        : _file_reader(file_reader),
92
75
          _read_table_columns(read_columns),
93
75
          _row_group_id(row_group_id),
94
75
          _row_group_meta(row_group),
95
75
          _remaining_rows(row_group.num_rows),
96
75
          _ctz(ctz),
97
75
          _io_ctx(io_ctx),
98
75
          _position_delete_ctx(position_delete_ctx),
99
75
          _lazy_read_ctx(lazy_read_ctx),
100
75
          _state(state),
101
75
          _obj_pool(new ObjectPool()),
102
75
          _column_ids(column_ids),
103
75
          _filter_column_ids(filter_column_ids) {}
104
105
75
RowGroupReader::~RowGroupReader() {
106
75
    if (_obj_pool != nullptr) {
107
75
        _obj_pool->clear();
108
75
    }
109
75
}
110
111
Status RowGroupReader::init(
112
        const FieldDescriptor& schema, RowRanges& row_ranges,
113
        std::unordered_map<int, tparquet::OffsetIndex>& col_offsets,
114
        const TupleDescriptor* tuple_descriptor, const RowDescriptor* row_descriptor,
115
        const std::unordered_map<std::string, int>* colname_to_slot_id,
116
        const VExprContextSPtrs* not_single_slot_filter_conjuncts,
117
74
        const std::unordered_map<int, VExprContextSPtrs>* slot_id_to_filter_conjuncts) {
118
74
    _tuple_descriptor = tuple_descriptor;
119
74
    _row_descriptor = row_descriptor;
120
74
    _col_name_to_slot_id = colname_to_slot_id;
121
74
    _slot_id_to_filter_conjuncts = slot_id_to_filter_conjuncts;
122
74
    _read_ranges = row_ranges;
123
74
    _filter_read_ranges_by_condition_cache();
124
74
    _remaining_rows = _read_ranges.count();
125
126
74
    if (_read_table_columns.empty()) {
127
        // Query task that only select columns in path.
128
1
        return Status::OK();
129
1
    }
130
73
    const size_t MAX_GROUP_BUF_SIZE = config::parquet_rowgroup_max_buffer_mb << 20;
131
73
    const size_t MAX_COLUMN_BUF_SIZE = config::parquet_column_max_buffer_mb << 20;
132
73
    size_t max_buf_size =
133
73
            std::min(MAX_COLUMN_BUF_SIZE, MAX_GROUP_BUF_SIZE / _read_table_columns.size());
134
160
    for (const auto& read_table_col : _read_table_columns) {
135
160
        auto read_file_col = _table_info_node_ptr->children_file_column_name(read_table_col);
136
160
        auto* field = schema.get_column(read_file_col);
137
160
        std::unique_ptr<ParquetColumnReader> reader;
138
160
        RETURN_IF_ERROR(ParquetColumnReader::create(
139
160
                _file_reader, field, _row_group_meta, _read_ranges, _ctz, _io_ctx, reader,
140
160
                max_buf_size, col_offsets, _state, false, _column_ids, _filter_column_ids,
141
160
                _preserve_binary_uuid));
142
160
        if (reader == nullptr) {
143
0
            VLOG_DEBUG << "Init row group(" << _row_group_id << ") reader failed";
144
0
            return Status::Corruption("Init row group reader failed");
145
0
        }
146
160
        _column_readers[read_table_col] = std::move(reader);
147
160
    }
148
149
73
    if (not_single_slot_filter_conjuncts != nullptr && !not_single_slot_filter_conjuncts->empty()) {
150
1
        for (const auto& conjunct : *not_single_slot_filter_conjuncts) {
151
1
            _block_dict_filter_for_slots(conjunct->root());
152
1
        }
153
1
        _filter_conjuncts.insert(_filter_conjuncts.end(), not_single_slot_filter_conjuncts->begin(),
154
1
                                 not_single_slot_filter_conjuncts->end());
155
1
    }
156
157
    // Check if single slot can be filtered by dict.
158
73
    if (_slot_id_to_filter_conjuncts && !_slot_id_to_filter_conjuncts->empty()) {
159
4
        const std::vector<std::string>& predicate_col_names =
160
4
                _lazy_read_ctx.predicate_columns.first;
161
4
        const std::vector<int>& predicate_col_slot_ids = _lazy_read_ctx.predicate_columns.second;
162
10
        for (size_t i = 0; i < predicate_col_names.size(); ++i) {
163
6
            const std::string& predicate_col_name = predicate_col_names[i];
164
6
            int slot_id = predicate_col_slot_ids[i];
165
166
6
            if (!_table_format_reader->has_column_optimization(
167
6
                        predicate_col_name,
168
6
                        TableFormatReader::ColumnOptimizationTypes::DICT_FILTER)) {
169
                // Row-lineage style generated columns cannot participate in dict filtering.
170
0
                if (_slot_id_to_filter_conjuncts->find(slot_id) !=
171
0
                    _slot_id_to_filter_conjuncts->end()) {
172
0
                    for (auto& ctx : _slot_id_to_filter_conjuncts->at(slot_id)) {
173
0
                        _filter_conjuncts.push_back(ctx);
174
0
                    }
175
0
                }
176
0
                continue;
177
0
            }
178
179
6
            auto predicate_file_col_name =
180
6
                    _table_info_node_ptr->children_file_column_name(predicate_col_name);
181
6
            auto field = schema.get_column(predicate_file_col_name);
182
6
            if (!_lazy_read_ctx.has_complex_type &&
183
6
                _can_filter_by_dict(
184
6
                        slot_id, _row_group_meta.columns[field->physical_column_index].meta_data)) {
185
1
                _dict_filter_cols.emplace_back(std::make_pair(predicate_col_name, slot_id));
186
5
            } else {
187
5
                if (_slot_id_to_filter_conjuncts->find(slot_id) !=
188
5
                    _slot_id_to_filter_conjuncts->end()) {
189
5
                    for (auto& ctx : _slot_id_to_filter_conjuncts->at(slot_id)) {
190
5
                        _filter_conjuncts.push_back(ctx);
191
5
                    }
192
5
                }
193
5
            }
194
6
        }
195
        // Add predicate_partition_columns in _slot_id_to_filter_conjuncts(single slot conjuncts)
196
        // to _filter_conjuncts, others should be added from not_single_slot_filter_conjuncts.
197
4
        for (auto& kv : _lazy_read_ctx.predicate_partition_columns) {
198
3
            auto& [value, slot_desc] = kv.second;
199
3
            auto iter = _slot_id_to_filter_conjuncts->find(slot_desc->id());
200
3
            if (iter != _slot_id_to_filter_conjuncts->end()) {
201
3
                for (auto& ctx : iter->second) {
202
3
                    _filter_conjuncts.push_back(ctx);
203
3
                }
204
3
            }
205
3
        }
206
        //For check missing column :   missing column == xx, missing column is null,missing column is not null.
207
4
        _filter_conjuncts.insert(_filter_conjuncts.end(),
208
4
                                 _lazy_read_ctx.missing_columns_conjuncts.begin(),
209
4
                                 _lazy_read_ctx.missing_columns_conjuncts.end());
210
4
        RETURN_IF_ERROR(_rewrite_dict_predicates());
211
4
    }
212
    // _state is nullptr in some ut.
213
73
    if (_state && _state->enable_adjust_conjunct_order_by_cost()) {
214
5
        std::ranges::stable_sort(_filter_conjuncts, [](const auto& a, const auto& b) {
215
3
            return a->execute_cost() < b->execute_cost();
216
3
        });
217
5
    }
218
73
    return Status::OK();
219
73
}
220
221
3
void RowGroupReader::_block_dict_filter_for_slots(const VExprSPtr& expr) {
222
3
    DORIS_CHECK(expr != nullptr);
223
3
    if (auto impl = expr->get_impl()) {
224
0
        _block_dict_filter_for_slots(impl);
225
0
        return;
226
0
    }
227
3
    if (expr->is_slot_ref()) {
228
2
        _dict_filter_blocked_slot_ids.insert(static_cast<const VSlotRef*>(expr.get())->slot_id());
229
2
        return;
230
2
    }
231
2
    for (const auto& child : expr->children()) {
232
2
        _block_dict_filter_for_slots(child);
233
2
    }
234
1
}
235
236
bool RowGroupReader::_can_filter_by_dict(int slot_id,
237
6
                                         const tparquet::ColumnMetaData& column_metadata) {
238
6
    if (_dict_filter_blocked_slot_ids.contains(slot_id)) {
239
2
        return false;
240
2
    }
241
4
    SlotDescriptor* slot = nullptr;
242
4
    const std::vector<SlotDescriptor*>& slots = _tuple_descriptor->slots();
243
9
    for (auto each : slots) {
244
9
        if (each->id() == slot_id) {
245
4
            slot = each;
246
4
            break;
247
4
        }
248
9
    }
249
4
    if (!is_string_type(slot->type()->get_primitive_type()) &&
250
4
        !is_var_len_object(slot->type()->get_primitive_type())) {
251
3
        return false;
252
3
    }
253
1
    if (column_metadata.type != tparquet::Type::BYTE_ARRAY) {
254
0
        return false;
255
0
    }
256
257
1
    if (!is_dictionary_encoded(column_metadata)) {
258
0
        return false;
259
0
    }
260
261
1
    if (_slot_id_to_filter_conjuncts->find(slot_id) == _slot_id_to_filter_conjuncts->end()) {
262
0
        return false;
263
0
    }
264
265
    // TODO: The current implementation of dictionary filtering does not take into account
266
    //  the implementation of NULL values because the dictionary itself does not contain
267
    //  NULL value encoding. As a result, many NULL-related functions or expressions
268
    //  cannot work properly, such as is null, is not null, coalesce, etc.
269
    //  Here we check if the predicate expr is IN or BINARY_PRED.
270
    //  Implementation of NULL value dictionary filtering will be carried out later.
271
1
    return std::ranges::all_of(_slot_id_to_filter_conjuncts->at(slot_id), [&](const auto& ctx) {
272
1
        return (ctx->root()->node_type() == TExprNodeType::IN_PRED ||
273
1
                ctx->root()->node_type() == TExprNodeType::BINARY_PRED) &&
274
1
               ctx->root()->children()[0]->node_type() == TExprNodeType::SLOT_REF;
275
1
    });
276
1
}
277
278
// This function is copied from
279
// https://github.com/apache/impala/blob/master/be/src/exec/parquet/hdfs-parquet-scanner.cc#L1717
280
2
bool RowGroupReader::is_dictionary_encoded(const tparquet::ColumnMetaData& column_metadata) {
281
    // The Parquet spec allows for column chunks to have mixed encodings
282
    // where some data pages are dictionary-encoded and others are plain
283
    // encoded. For example, a Parquet file writer might start writing
284
    // a column chunk as dictionary encoded, but it will switch to plain
285
    // encoding if the dictionary grows too large.
286
    //
287
    // In order for dictionary filters to skip the entire row group,
288
    // the conjuncts must be evaluated on column chunks that are entirely
289
    // encoded with the dictionary encoding. There are two checks
290
    // available to verify this:
291
    // 1. The encoding_stats field on the column chunk metadata provides
292
    //    information about the number of data pages written in each
293
    //    format. This allows for a specific check of whether all the
294
    //    data pages are dictionary encoded.
295
    // 2. The encodings field on the column chunk metadata lists the
296
    //    encodings used. If this list contains the dictionary encoding
297
    //    and does not include unexpected encodings (i.e. encodings not
298
    //    associated with definition/repetition levels), then it is entirely
299
    //    dictionary encoded.
300
2
    if (column_metadata.__isset.encoding_stats) {
301
        // Condition #1 above
302
4
        for (const tparquet::PageEncodingStats& enc_stat : column_metadata.encoding_stats) {
303
4
            if ((enc_stat.page_type == tparquet::PageType::DATA_PAGE ||
304
4
                 enc_stat.page_type == tparquet::PageType::DATA_PAGE_V2) &&
305
4
                (enc_stat.encoding != tparquet::Encoding::PLAIN_DICTIONARY &&
306
3
                 enc_stat.encoding != tparquet::Encoding::RLE_DICTIONARY) &&
307
4
                enc_stat.count > 0) {
308
1
                return false;
309
1
            }
310
4
        }
311
2
    } else {
312
        // Condition #2 above
313
0
        bool has_dict_encoding = false;
314
0
        bool has_nondict_encoding = false;
315
0
        for (const tparquet::Encoding::type& encoding : column_metadata.encodings) {
316
0
            if (encoding == tparquet::Encoding::PLAIN_DICTIONARY ||
317
0
                encoding == tparquet::Encoding::RLE_DICTIONARY) {
318
0
                has_dict_encoding = true;
319
0
            }
320
321
            // RLE and BIT_PACKED are used for repetition/definition levels
322
0
            if (encoding != tparquet::Encoding::PLAIN_DICTIONARY &&
323
0
                encoding != tparquet::Encoding::RLE_DICTIONARY &&
324
0
                encoding != tparquet::Encoding::RLE && encoding != tparquet::Encoding::BIT_PACKED) {
325
0
                has_nondict_encoding = true;
326
0
                break;
327
0
            }
328
0
        }
329
        // Not entirely dictionary encoded if:
330
        // 1. No dictionary encoding listed
331
        // OR
332
        // 2. Some non-dictionary encoding is listed
333
0
        if (!has_dict_encoding || has_nondict_encoding) {
334
0
            return false;
335
0
        }
336
0
    }
337
338
1
    return true;
339
2
}
340
341
Status RowGroupReader::next_batch(Block* block, size_t batch_size, size_t* read_rows,
342
124
                                  bool* batch_eof) {
343
124
    if (_is_row_group_filtered) {
344
0
        *read_rows = 0;
345
0
        *batch_eof = true;
346
0
        return Status::OK();
347
0
    }
348
349
    // Process external table query task that select columns are all from path.
350
124
    if (_read_table_columns.empty()) {
351
11
        int64_t batch_base_row = _total_read_rows;
352
11
        RETURN_IF_ERROR(_read_empty_batch(batch_size, read_rows, batch_eof));
353
354
11
        DCHECK(_table_format_reader);
355
11
        RETURN_IF_ERROR(_table_format_reader->on_fill_partition_columns(
356
11
                block, *read_rows, _lazy_read_ctx.partition_col_names));
357
11
        RETURN_IF_ERROR(_table_format_reader->on_fill_missing_columns(
358
11
                block, *read_rows, _lazy_read_ctx.missing_col_names));
359
11
        RETURN_IF_ERROR(_table_format_reader->fill_synthesized_columns(block, *read_rows));
360
11
        RETURN_IF_ERROR(_table_format_reader->fill_generated_columns(block, *read_rows));
361
11
        std::vector<uint32_t> columns_to_filter(block->columns());
362
22
        for (uint32_t i = 0; i < columns_to_filter.size(); ++i) {
363
11
            columns_to_filter[i] = i;
364
11
        }
365
11
        IColumn::Filter result_filter;
366
11
        RETURN_IF_ERROR(VExprContext::execute_conjuncts_and_filter_block(
367
11
                _lazy_read_ctx.conjuncts, block, columns_to_filter, block->columns(),
368
11
                result_filter));
369
11
        _mark_condition_cache_granules(result_filter.data(), *read_rows, batch_base_row);
370
11
        *read_rows = block->rows();
371
11
        return Status::OK();
372
11
    }
373
113
    if (_lazy_read_ctx.can_lazy_read) {
374
        // call _do_lazy_read recursively when current batch is skipped
375
12
        return _do_lazy_read(block, batch_size, read_rows, batch_eof);
376
101
    } else {
377
101
        FilterMap filter_map;
378
101
        int64_t batch_base_row = _total_read_rows;
379
101
        RETURN_IF_ERROR((_read_column_data(block, _lazy_read_ctx.all_read_columns, batch_size,
380
101
                                           read_rows, batch_eof, filter_map)));
381
101
        DCHECK(_table_format_reader);
382
101
        RETURN_IF_ERROR(_table_format_reader->on_fill_partition_columns(
383
101
                block, *read_rows, _lazy_read_ctx.partition_col_names));
384
101
        RETURN_IF_ERROR(_table_format_reader->on_fill_missing_columns(
385
101
                block, *read_rows, _lazy_read_ctx.missing_col_names));
386
387
101
        if (_need_current_batch_row_positions()) {
388
8
            RETURN_IF_ERROR(_get_current_batch_row_id(*read_rows));
389
8
        }
390
101
        RETURN_IF_ERROR(_table_format_reader->fill_synthesized_columns(block, *read_rows));
391
101
        RETURN_IF_ERROR(_table_format_reader->fill_generated_columns(block, *read_rows));
392
393
101
#ifndef NDEBUG
394
237
        for (auto col : *block) {
395
237
            col.column->sanity_check();
396
237
            DCHECK(block->rows() == col.column->size())
397
0
                    << absl::Substitute("block rows = $0 , column rows = $1, col name = $2",
398
0
                                        block->rows(), col.column->size(), col.name);
399
237
        }
400
101
#endif
401
402
101
        if (block->rows() == 0) {
403
0
            RETURN_IF_ERROR(_convert_dict_cols_to_string_cols(block));
404
0
            *read_rows = block->rows();
405
0
#ifndef NDEBUG
406
0
            for (auto col : *block) {
407
0
                col.column->sanity_check();
408
0
                DCHECK(block->rows() == col.column->size())
409
0
                        << absl::Substitute("block rows = $0 , column rows = $1, col name = $2",
410
0
                                            block->rows(), col.column->size(), col.name);
411
0
            }
412
0
#endif
413
0
            return Status::OK();
414
0
        }
415
101
        {
416
101
            SCOPED_RAW_TIMER(&_predicate_filter_time);
417
101
            RETURN_IF_ERROR(_build_pos_delete_filter(*read_rows));
418
419
101
            std::vector<uint32_t> columns_to_filter;
420
101
            int column_to_keep = block->columns();
421
101
            columns_to_filter.resize(column_to_keep);
422
338
            for (uint32_t i = 0; i < column_to_keep; ++i) {
423
237
                columns_to_filter[i] = i;
424
237
            }
425
101
            if (!_lazy_read_ctx.conjuncts.empty()) {
426
12
                std::vector<IColumn::Filter*> filters;
427
12
                if (_position_delete_ctx.has_filter) {
428
0
                    filters.push_back(_pos_delete_filter_ptr.get());
429
0
                }
430
12
                IColumn::Filter result_filter(block->rows(), 1);
431
12
                bool can_filter_all = false;
432
433
12
                {
434
12
                    RETURN_IF_ERROR_OR_CATCH_EXCEPTION(VExprContext::execute_conjuncts(
435
12
                            _filter_conjuncts, &filters, block, &result_filter, &can_filter_all));
436
12
                }
437
438
                // Condition cache MISS: mark granules with surviving rows (non-lazy path)
439
12
                if (!can_filter_all) {
440
12
                    _mark_condition_cache_granules(result_filter.data(), block->rows(),
441
12
                                                   batch_base_row);
442
12
                }
443
444
12
                if (can_filter_all) {
445
0
                    block->clear_column_data(columns_to_filter);
446
0
                    Block::erase_useless_column(block, column_to_keep);
447
0
                    RETURN_IF_ERROR(_convert_dict_cols_to_string_cols(block));
448
0
                    return Status::OK();
449
0
                }
450
451
12
                RETURN_IF_CATCH_EXCEPTION(
452
12
                        Block::filter_block_internal(block, columns_to_filter, result_filter));
453
12
                Block::erase_useless_column(block, column_to_keep);
454
89
            } else {
455
89
                RETURN_IF_CATCH_EXCEPTION(
456
89
                        RETURN_IF_ERROR(_filter_block(block, column_to_keep, columns_to_filter)));
457
89
            }
458
101
            RETURN_IF_ERROR(_convert_dict_cols_to_string_cols(block));
459
101
        }
460
101
#ifndef NDEBUG
461
237
        for (auto col : *block) {
462
237
            col.column->sanity_check();
463
237
            DCHECK(block->rows() == col.column->size())
464
0
                    << absl::Substitute("block rows = $0 , column rows = $1, col name = $2",
465
0
                                        block->rows(), col.column->size(), col.name);
466
237
        }
467
101
#endif
468
101
        *read_rows = block->rows();
469
101
        return Status::OK();
470
101
    }
471
113
}
472
473
// Maps each batch row to its global parquet file position via _read_ranges, then marks
474
// the corresponding condition cache granule as true if the filter indicates the row survived.
475
// batch_seq_start is the number of rows already read sequentially before this batch
476
// (i.e., _total_read_rows before the batch started).
477
void RowGroupReader::_mark_condition_cache_granules(const uint8_t* filter_data, size_t num_rows,
478
34
                                                    int64_t batch_seq_start) {
479
34
    if (!_condition_cache_ctx || _condition_cache_ctx->is_hit) {
480
34
        return;
481
34
    }
482
0
    auto& cache = *_condition_cache_ctx->filter_result;
483
0
    for (size_t i = 0; i < num_rows; i++) {
484
0
        if (filter_data[i]) {
485
            // row-group-relative position of this row
486
0
            int64_t rg_pos = _read_ranges.get_row_index_by_pos(batch_seq_start + i);
487
            // global row number in the parquet file
488
0
            size_t granule = (_current_row_group_idx.first_row + rg_pos) /
489
0
                             ConditionCacheContext::GRANULE_SIZE;
490
0
            size_t cache_idx = granule - _condition_cache_ctx->base_granule;
491
0
            if (cache_idx < cache.size()) {
492
0
                cache[cache_idx] = true;
493
0
            }
494
0
        }
495
0
    }
496
0
}
497
498
// On condition cache HIT, removes row ranges whose granules have no surviving rows from
499
// _read_ranges BEFORE column readers are created. This makes ParquetColumnReader skip I/O
500
// entirely for false-granule rows — both predicate and lazy columns — via its existing
501
// page/row-skipping infrastructure.
502
74
void RowGroupReader::_filter_read_ranges_by_condition_cache() {
503
74
    if (!_condition_cache_ctx || !_condition_cache_ctx->is_hit) {
504
74
        return;
505
74
    }
506
0
    auto& filter_result = *_condition_cache_ctx->filter_result;
507
0
    if (filter_result.empty()) {
508
0
        return;
509
0
    }
510
511
0
    auto old_row_count = _read_ranges.count();
512
0
    _read_ranges =
513
0
            filter_ranges_by_cache(_read_ranges, filter_result, _current_row_group_idx.first_row,
514
0
                                   _condition_cache_ctx->base_granule);
515
0
    _is_row_group_filtered = _read_ranges.is_empty();
516
0
    _condition_cache_filtered_rows += old_row_count - _read_ranges.count();
517
0
}
518
519
// Filters read_ranges by removing rows whose cache granule is false.
520
//
521
// Cache index i maps to global granule (base_granule + i), which covers global file
522
// rows [(base_granule+i)*GS, (base_granule+i+1)*GS). Since read_ranges uses
523
// row-group-relative indices and first_row is the global position of the row group's
524
// first row, global granule g maps to row-group-relative range:
525
//   [max(0, g*GS - first_row), max(0, (g+1)*GS - first_row))
526
//
527
// We build a RowRanges of all false-granule regions (in row-group-relative coordinates),
528
// then subtract from read_ranges via ranges_exception.
529
//
530
// Granules beyond cache.size() are kept conservatively (assumed true).
531
//
532
// When base_granule > 0, the cache only covers granules starting from base_granule.
533
// This happens when a Parquet file is split across multiple scan ranges and this reader
534
// only processes row groups starting at a non-zero offset in the file.
535
RowRanges RowGroupReader::filter_ranges_by_cache(const RowRanges& read_ranges,
536
                                                 const std::vector<bool>& cache, int64_t first_row,
537
21
                                                 int64_t base_granule) {
538
21
    constexpr int64_t GS = ConditionCacheContext::GRANULE_SIZE;
539
21
    RowRanges filtered_ranges;
540
541
138
    for (size_t i = 0; i < cache.size(); i++) {
542
117
        if (!cache[i]) {
543
64
            int64_t global_granule = base_granule + static_cast<int64_t>(i);
544
64
            int64_t rg_from = std::max(static_cast<int64_t>(0), global_granule * GS - first_row);
545
64
            int64_t rg_to =
546
64
                    std::max(static_cast<int64_t>(0), (global_granule + 1) * GS - first_row);
547
64
            if (rg_from < rg_to) {
548
16
                filtered_ranges.add(RowRange(rg_from, rg_to));
549
16
            }
550
64
        }
551
117
    }
552
553
21
    RowRanges result;
554
21
    RowRanges::ranges_exception(read_ranges, filtered_ranges, &result);
555
21
    return result;
556
21
}
557
558
Status RowGroupReader::_read_column_data(Block* block,
559
                                         const std::vector<std::string>& table_columns,
560
                                         size_t batch_size, size_t* read_rows, bool* batch_eof,
561
134
                                         FilterMap& filter_map) {
562
134
    size_t batch_read_rows = 0;
563
134
    bool has_eof = false;
564
249
    for (auto& read_col_name : table_columns) {
565
249
        uint32_t block_pos = 0;
566
249
        RETURN_IF_ERROR(_get_block_column_pos(*block, read_col_name, &block_pos));
567
249
        auto reader_iter = _column_readers.find(read_col_name);
568
249
        if (reader_iter == _column_readers.end() || reader_iter->second == nullptr) {
569
0
            return Status::InternalError("Column reader for '{}' not found in parquet row group",
570
0
                                         read_col_name);
571
0
        }
572
573
249
        auto& column_with_type_and_name = block->safe_get_by_position(block_pos);
574
249
        auto& column_ptr = column_with_type_and_name.column;
575
249
        auto& column_type = column_with_type_and_name.type;
576
249
        bool is_dict_filter = false;
577
249
        for (auto& _dict_filter_col : _dict_filter_cols) {
578
3
            if (_dict_filter_col.first == read_col_name) {
579
1
                MutableColumnPtr dict_column = ColumnInt32::create();
580
1
                if (column_type->is_nullable()) {
581
0
                    block->get_by_position(block_pos).type =
582
0
                            std::make_shared<DataTypeNullable>(std::make_shared<DataTypeInt32>());
583
0
                    block->replace_by_position(
584
0
                            block_pos,
585
0
                            ColumnNullable::create(std::move(dict_column),
586
0
                                                   ColumnUInt8::create(dict_column->size(), 0)));
587
1
                } else {
588
1
                    block->get_by_position(block_pos).type = std::make_shared<DataTypeInt32>();
589
1
                    block->replace_by_position(block_pos, std::move(dict_column));
590
1
                }
591
1
                is_dict_filter = true;
592
1
                break;
593
1
            }
594
3
        }
595
596
249
        size_t col_read_rows = 0;
597
249
        bool col_eof = false;
598
        // Should reset _filter_map_index to 0 when reading next column.
599
        //        select_vector.reset();
600
249
        reader_iter->second->reset_filter_map_index();
601
561
        while (!col_eof && col_read_rows < batch_size) {
602
312
            size_t loop_rows = 0;
603
312
            RETURN_IF_ERROR(reader_iter->second->read_column_data(
604
312
                    column_ptr, column_type, _table_info_node_ptr->get_children_node(read_col_name),
605
312
                    filter_map, batch_size - col_read_rows, &loop_rows, &col_eof, is_dict_filter));
606
312
            VLOG_DEBUG << "[RowGroupReader] column '" << read_col_name
607
0
                       << "' loop_rows=" << loop_rows << " col_read_rows_so_far=" << col_read_rows
608
0
                       << std::endl;
609
312
            col_read_rows += loop_rows;
610
312
        }
611
249
        VLOG_DEBUG << "[RowGroupReader] column '" << read_col_name
612
0
                   << "' read_rows=" << col_read_rows << std::endl;
613
249
        if (batch_read_rows > 0 && batch_read_rows != col_read_rows) {
614
0
            LOG(WARNING) << "[RowGroupReader] Mismatched read rows among parquet columns. "
615
0
                            "previous_batch_read_rows="
616
0
                         << batch_read_rows << ", current_column='" << read_col_name
617
0
                         << "', current_col_read_rows=" << col_read_rows;
618
0
            return Status::Corruption("Can't read the same number of rows among parquet columns");
619
0
        }
620
249
        batch_read_rows = col_read_rows;
621
622
249
#ifndef NDEBUG
623
249
        column_ptr->sanity_check();
624
249
#endif
625
249
        if (col_eof) {
626
159
            has_eof = true;
627
159
        }
628
249
    }
629
630
134
    *read_rows = batch_read_rows;
631
134
    *batch_eof = has_eof;
632
633
134
    return Status::OK();
634
134
}
635
636
Status RowGroupReader::_do_lazy_read(Block* block, size_t batch_size, size_t* read_rows,
637
12
                                     bool* batch_eof) {
638
12
    std::unique_ptr<FilterMap> filter_map_ptr = nullptr;
639
12
    size_t pre_read_rows;
640
12
    bool pre_eof;
641
12
    std::vector<uint32_t> columns_to_filter;
642
12
    uint32_t origin_column_num = block->columns();
643
12
    columns_to_filter.resize(origin_column_num);
644
48
    for (uint32_t i = 0; i < origin_column_num; ++i) {
645
36
        columns_to_filter[i] = i;
646
36
    }
647
12
    IColumn::Filter result_filter;
648
12
    size_t pre_raw_read_rows = 0;
649
22
    while (!_state->is_cancelled()) {
650
        // read predicate columns
651
22
        pre_read_rows = 0;
652
22
        pre_eof = false;
653
22
        FilterMap filter_map;
654
22
        int64_t batch_base_row = _total_read_rows;
655
22
        RETURN_IF_ERROR(_read_column_data(block, _lazy_read_ctx.predicate_columns.first, batch_size,
656
22
                                          &pre_read_rows, &pre_eof, filter_map));
657
22
        if (pre_read_rows == 0) {
658
0
            DCHECK_EQ(pre_eof, true);
659
0
            break;
660
0
        }
661
22
        pre_raw_read_rows += pre_read_rows;
662
663
22
        DCHECK(_table_format_reader);
664
22
        RETURN_IF_ERROR(_table_format_reader->on_fill_partition_columns(
665
22
                block, pre_read_rows, _lazy_read_ctx.predicate_partition_col_names));
666
22
        RETURN_IF_ERROR(_table_format_reader->on_fill_missing_columns(
667
22
                block, pre_read_rows, _lazy_read_ctx.predicate_missing_col_names));
668
22
        if (_need_current_batch_row_positions()) {
669
0
            RETURN_IF_ERROR(_get_current_batch_row_id(pre_read_rows));
670
0
        }
671
22
        RETURN_IF_ERROR(_table_format_reader->fill_synthesized_columns(block, pre_read_rows));
672
22
        RETURN_IF_ERROR(_table_format_reader->fill_generated_columns(block, pre_read_rows));
673
22
        RETURN_IF_ERROR(_build_pos_delete_filter(pre_read_rows));
674
675
22
#ifndef NDEBUG
676
66
        for (auto col : *block) {
677
66
            if (col.column->size() == 0) { // lazy read column.
678
22
                continue;
679
22
            }
680
44
            col.column->sanity_check();
681
44
            DCHECK(pre_read_rows == col.column->size())
682
0
                    << absl::Substitute("pre_read_rows = $0 , column rows = $1, col name = $2",
683
0
                                        pre_read_rows, col.column->size(), col.name);
684
44
        }
685
22
#endif
686
687
22
        bool can_filter_all = false;
688
22
        {
689
22
            SCOPED_RAW_TIMER(&_predicate_filter_time);
690
691
            // generate filter vector
692
22
            if (_lazy_read_ctx.resize_first_column) {
693
                // VExprContext.execute has an optimization, the filtering is executed when block->rows() > 0
694
                // The following process may be tricky and time-consuming, but we have no other way.
695
22
                auto column_guard = block->mutate_column_scoped(0);
696
22
                column_guard.mutable_column()->resize(pre_read_rows);
697
22
            }
698
22
            result_filter.assign(pre_read_rows, static_cast<unsigned char>(1));
699
22
            std::vector<IColumn::Filter*> filters;
700
22
            if (_position_delete_ctx.has_filter) {
701
0
                filters.push_back(_pos_delete_filter_ptr.get());
702
0
            }
703
704
22
            VExprContextSPtrs filter_contexts;
705
44
            for (auto& conjunct : _filter_conjuncts) {
706
44
                filter_contexts.emplace_back(conjunct);
707
44
            }
708
709
22
            {
710
22
                RETURN_IF_ERROR(VExprContext::execute_conjuncts(filter_contexts, &filters, block,
711
22
                                                                &result_filter, &can_filter_all));
712
22
            }
713
714
            // Condition cache MISS: mark granules with surviving rows
715
22
            if (!can_filter_all) {
716
11
                _mark_condition_cache_granules(result_filter.data(), pre_read_rows, batch_base_row);
717
11
            }
718
719
22
            if (_lazy_read_ctx.resize_first_column) {
720
                // We have to clean the first column to insert right data.
721
22
                block->clear_column_data(std::vector<uint32_t> {0});
722
22
            }
723
22
        }
724
725
0
        const uint8_t* __restrict filter_map_data = result_filter.data();
726
22
        filter_map_ptr = std::make_unique<FilterMap>();
727
22
        RETURN_IF_ERROR(filter_map_ptr->init(filter_map_data, pre_read_rows, can_filter_all));
728
22
        if (filter_map_ptr->filter_all()) {
729
11
            {
730
11
                SCOPED_RAW_TIMER(&_predicate_filter_time);
731
11
                std::vector<uint32_t> columns_to_clear;
732
11
                columns_to_clear.reserve(_lazy_read_ctx.predicate_columns.first.size() +
733
11
                                         _lazy_read_ctx.predicate_partition_columns.size() +
734
11
                                         _lazy_read_ctx.predicate_missing_columns.size());
735
11
                for (const auto& col : _lazy_read_ctx.predicate_columns.first) {
736
                    // clean block to read predicate columns
737
11
                    uint32_t block_pos = 0;
738
11
                    RETURN_IF_ERROR(_get_block_column_pos(*block, col, &block_pos));
739
11
                    columns_to_clear.emplace_back(block_pos);
740
11
                }
741
11
                for (const auto& col : _lazy_read_ctx.predicate_partition_columns) {
742
11
                    uint32_t block_pos = 0;
743
11
                    RETURN_IF_ERROR(_get_block_column_pos(*block, col.first, &block_pos));
744
11
                    columns_to_clear.emplace_back(block_pos);
745
11
                }
746
11
                for (const auto& col : _lazy_read_ctx.predicate_missing_columns) {
747
0
                    uint32_t block_pos = 0;
748
0
                    RETURN_IF_ERROR(_get_block_column_pos(*block, col.first, &block_pos));
749
0
                    columns_to_clear.emplace_back(block_pos);
750
0
                }
751
11
                block->clear_column_data(columns_to_clear);
752
11
                RETURN_IF_ERROR(_table_format_reader->clear_synthesized_columns(block));
753
11
                RETURN_IF_ERROR(_table_format_reader->clear_generated_columns(block));
754
11
                Block::erase_useless_column(block, origin_column_num);
755
11
            }
756
757
11
            if (!pre_eof) {
758
                // If continuous batches are skipped, we can cache them to skip a whole page
759
10
                _cached_filtered_rows += pre_read_rows;
760
10
                if (pre_raw_read_rows >= config::doris_scanner_row_num) {
761
0
                    *read_rows = 0;
762
0
                    RETURN_IF_ERROR(_convert_dict_cols_to_string_cols(block));
763
0
                    return Status::OK();
764
0
                }
765
10
            } else { // pre_eof
766
                // If filter_map_ptr->filter_all() and pre_eof, we can skip whole row group.
767
1
                *read_rows = 0;
768
1
                *batch_eof = true;
769
1
                _lazy_read_filtered_rows += (pre_read_rows + _cached_filtered_rows);
770
1
                RETURN_IF_ERROR(_convert_dict_cols_to_string_cols(block));
771
1
                return Status::OK();
772
1
            }
773
11
        } else {
774
11
            break;
775
11
        }
776
22
    }
777
11
    if (_state->is_cancelled()) {
778
0
        return Status::Cancelled("cancelled");
779
0
    }
780
781
11
    if (filter_map_ptr == nullptr) {
782
0
        DCHECK_EQ(pre_read_rows + _cached_filtered_rows, 0);
783
0
        *read_rows = 0;
784
0
        *batch_eof = true;
785
0
        RETURN_IF_ERROR(_convert_dict_cols_to_string_cols(block));
786
0
        return Status::OK();
787
0
    }
788
789
11
    FilterMap& filter_map = *filter_map_ptr;
790
11
    DorisUniqueBufferPtr<uint8_t> rebuild_filter_map = nullptr;
791
11
    if (_cached_filtered_rows != 0) {
792
0
        RETURN_IF_ERROR(_rebuild_filter_map(filter_map, rebuild_filter_map, pre_read_rows));
793
0
        pre_read_rows += _cached_filtered_rows;
794
0
        _cached_filtered_rows = 0;
795
0
    }
796
797
    // lazy read columns
798
11
    size_t lazy_read_rows;
799
11
    bool lazy_eof;
800
11
    RETURN_IF_ERROR(_read_column_data(block, _lazy_read_ctx.lazy_read_columns, pre_read_rows,
801
11
                                      &lazy_read_rows, &lazy_eof, filter_map));
802
803
11
    if (pre_read_rows != lazy_read_rows) {
804
0
        return Status::Corruption("Can't read the same number of rows when doing lazy read");
805
0
    }
806
    // pre_eof ^ lazy_eof
807
    // we set pre_read_rows as batch_size for lazy read columns, so pre_eof != lazy_eof
808
809
    // filter data in predicate columns, and remove filter column
810
11
    {
811
11
        SCOPED_RAW_TIMER(&_predicate_filter_time);
812
11
        if (filter_map.has_filter()) {
813
0
            RETURN_IF_CATCH_EXCEPTION(Block::filter_block_internal(
814
0
                    block, _lazy_read_ctx.all_predicate_col_ids, result_filter));
815
0
            Block::erase_useless_column(block, origin_column_num);
816
817
11
        } else {
818
11
            Block::erase_useless_column(block, origin_column_num);
819
11
        }
820
11
    }
821
822
11
    RETURN_IF_ERROR(_convert_dict_cols_to_string_cols(block));
823
824
11
    size_t column_num = block->columns();
825
11
    size_t column_size = 0;
826
44
    for (int i = 0; i < column_num; ++i) {
827
33
        size_t cz = block->get_by_position(i).column->size();
828
33
        if (column_size != 0 && cz != 0) {
829
22
            DCHECK_EQ(column_size, cz);
830
22
        }
831
33
        if (cz != 0) {
832
33
            column_size = cz;
833
33
        }
834
33
    }
835
11
    _lazy_read_filtered_rows += pre_read_rows - column_size;
836
11
    *read_rows = column_size;
837
838
11
    *batch_eof = pre_eof;
839
11
    DCHECK(_table_format_reader);
840
11
    RETURN_IF_ERROR(_table_format_reader->on_fill_partition_columns(
841
11
            block, column_size, _lazy_read_ctx.partition_col_names));
842
11
    RETURN_IF_ERROR(_table_format_reader->on_fill_missing_columns(
843
11
            block, column_size, _lazy_read_ctx.missing_col_names));
844
11
#ifndef NDEBUG
845
33
    for (auto col : *block) {
846
33
        col.column->sanity_check();
847
33
        DCHECK(block->rows() == col.column->size())
848
0
                << absl::Substitute("block rows = $0 , column rows = $1, col name = $2",
849
0
                                    block->rows(), col.column->size(), col.name);
850
33
    }
851
11
#endif
852
11
    return Status::OK();
853
11
}
854
855
Status RowGroupReader::_rebuild_filter_map(FilterMap& filter_map,
856
                                           DorisUniqueBufferPtr<uint8_t>& filter_map_data,
857
0
                                           size_t pre_read_rows) const {
858
0
    if (_cached_filtered_rows == 0) {
859
0
        return Status::OK();
860
0
    }
861
0
    size_t total_rows = _cached_filtered_rows + pre_read_rows;
862
0
    if (filter_map.filter_all()) {
863
0
        RETURN_IF_ERROR(filter_map.init(nullptr, total_rows, true));
864
0
        return Status::OK();
865
0
    }
866
867
0
    filter_map_data = make_unique_buffer<uint8_t>(total_rows);
868
0
    auto* map = filter_map_data.get();
869
0
    for (size_t i = 0; i < _cached_filtered_rows; ++i) {
870
0
        map[i] = 0;
871
0
    }
872
0
    const uint8_t* old_map = filter_map.filter_map_data();
873
0
    if (old_map == nullptr) {
874
        // select_vector.filter_all() == true is already built.
875
0
        for (size_t i = _cached_filtered_rows; i < total_rows; ++i) {
876
0
            map[i] = 1;
877
0
        }
878
0
    } else {
879
0
        memcpy(map + _cached_filtered_rows, old_map, pre_read_rows);
880
0
    }
881
0
    RETURN_IF_ERROR(filter_map.init(map, total_rows, false));
882
0
    return Status::OK();
883
0
}
884
885
Status RowGroupReader::_fill_partition_columns(
886
        Block* block, size_t rows,
887
        const std::unordered_map<std::string, std::tuple<std::string, const SlotDescriptor*>>&
888
0
                partition_columns) {
889
0
    DataTypeSerDe::FormatOptions _text_formatOptions;
890
0
    for (const auto& kv : partition_columns) {
891
0
        uint32_t block_pos = 0;
892
0
        RETURN_IF_ERROR(_get_block_column_pos(*block, kv.first, &block_pos));
893
0
        auto doris_column = block->get_by_position(block_pos).column;
894
        // obtained from block*, it is a mutable object.
895
0
        auto* col_ptr = const_cast<IColumn*>(doris_column.get());
896
0
        const auto& [value, slot_desc] = kv.second;
897
0
        auto _text_serde = slot_desc->get_data_type_ptr()->get_serde();
898
0
        Slice slice(value.data(), value.size());
899
0
        uint64_t num_deserialized = 0;
900
        // Be careful when reading empty rows from parquet row groups.
901
0
        if (_text_serde->deserialize_column_from_fixed_json(*col_ptr, slice, rows,
902
0
                                                            &num_deserialized,
903
0
                                                            _text_formatOptions) != Status::OK()) {
904
0
            return Status::InternalError("Failed to fill partition column: {}={}",
905
0
                                         slot_desc->col_name(), value);
906
0
        }
907
0
        if (num_deserialized != rows) {
908
0
            return Status::InternalError(
909
0
                    "Failed to fill partition column: {}={} ."
910
0
                    "Number of rows expected to be written : {}, number of rows actually written : "
911
0
                    "{}",
912
0
                    slot_desc->col_name(), value, num_deserialized, rows);
913
0
        }
914
0
    }
915
0
    return Status::OK();
916
0
}
917
918
Status RowGroupReader::_fill_missing_columns(
919
        Block* block, size_t rows,
920
0
        const std::unordered_map<std::string, VExprContextSPtr>& missing_columns) {
921
0
    for (const auto& kv : missing_columns) {
922
0
        uint32_t block_pos = 0;
923
0
        RETURN_IF_ERROR(_get_block_column_pos(*block, kv.first, &block_pos));
924
0
        if (kv.second == nullptr) {
925
            // no default column, fill with null
926
0
            auto column_guard = block->mutate_column_scoped(block_pos);
927
0
            auto& mutable_column = column_guard.mutable_column();
928
0
            auto* nullable_column = assert_cast<ColumnNullable*>(mutable_column.get());
929
0
            nullable_column->insert_many_defaults(rows);
930
0
        } else {
931
            // fill with default value
932
0
            const auto& ctx = kv.second;
933
0
            ColumnPtr result_column_ptr;
934
            // PT1 => dest primitive type
935
0
            RETURN_IF_ERROR(ctx->execute(block, result_column_ptr));
936
0
            if (result_column_ptr->use_count() == 1) {
937
                // call resize because the first column of _src_block_ptr may not be filled by reader,
938
                // so _src_block_ptr->rows() may return wrong result, cause the column created by `ctx->execute()`
939
                // has only one row.
940
0
                auto mutable_column = result_column_ptr->assert_mutable();
941
0
                mutable_column->resize(rows);
942
                // result_column_ptr maybe a ColumnConst, convert it to a normal column
943
0
                result_column_ptr = result_column_ptr->convert_to_full_column_if_const();
944
0
                auto origin_column_type = block->get_by_position(block_pos).type;
945
0
                bool is_nullable = origin_column_type->is_nullable();
946
0
                block->replace_by_position(block_pos, is_nullable ? make_nullable(result_column_ptr)
947
0
                                                                  : result_column_ptr);
948
0
            }
949
0
        }
950
0
    }
951
0
    return Status::OK();
952
0
}
953
954
Status RowGroupReader::_get_block_column_pos(const Block& block, const std::string& column_name,
955
272
                                             uint32_t* position) const {
956
272
    if (_col_name_to_block_idx == nullptr) {
957
0
        return Status::InternalError(
958
0
                "Column name to block index map is not set when reading parquet column '{}', "
959
0
                "block: "
960
0
                "{}",
961
0
                column_name, block.dump_structure());
962
0
    }
963
272
    auto iter = _col_name_to_block_idx->find(column_name);
964
272
    if (iter == _col_name_to_block_idx->end()) {
965
0
        return Status::InternalError("Column '{}' not found in block index map, block: {}",
966
0
                                     column_name, block.dump_structure());
967
0
    }
968
272
    if (iter->second >= block.columns()) {
969
0
        return Status::InternalError(
970
0
                "Column '{}' maps to invalid block position {}, block columns: {}, block: {}",
971
0
                column_name, iter->second, block.columns(), block.dump_structure());
972
0
    }
973
272
    *position = iter->second;
974
272
    return Status::OK();
975
272
}
976
977
134
bool RowGroupReader::_need_current_batch_row_positions() const {
978
134
    DCHECK(_table_format_reader);
979
134
    return _table_format_reader->has_synthesized_column_handlers() ||
980
134
           _table_format_reader->has_generated_column_handlers();
981
134
}
982
983
11
Status RowGroupReader::_read_empty_batch(size_t batch_size, size_t* read_rows, bool* batch_eof) {
984
11
    if (_position_delete_ctx.has_filter) {
985
0
        int64_t start_row_id = _position_delete_ctx.current_row_id;
986
0
        int64_t end_row_id = std::min(_position_delete_ctx.current_row_id + (int64_t)batch_size,
987
0
                                      _position_delete_ctx.last_row_id);
988
0
        int64_t num_delete_rows = 0;
989
0
        auto before_index = _position_delete_ctx.index;
990
0
        while (_position_delete_ctx.index < _position_delete_ctx.end_index) {
991
0
            const int64_t& delete_row_id =
992
0
                    _position_delete_ctx.delete_rows[_position_delete_ctx.index];
993
0
            if (delete_row_id < start_row_id) {
994
0
                _position_delete_ctx.index++;
995
0
                before_index = _position_delete_ctx.index;
996
0
            } else if (delete_row_id < end_row_id) {
997
0
                num_delete_rows++;
998
0
                _position_delete_ctx.index++;
999
0
            } else { // delete_row_id >= end_row_id
1000
0
                break;
1001
0
            }
1002
0
        }
1003
0
        *read_rows = end_row_id - start_row_id - num_delete_rows;
1004
0
        _position_delete_ctx.current_row_id = end_row_id;
1005
0
        *batch_eof = _position_delete_ctx.current_row_id == _position_delete_ctx.last_row_id;
1006
1007
0
        if (_need_current_batch_row_positions()) {
1008
0
            _current_batch_row_ids.clear();
1009
0
            _current_batch_row_ids.resize(*read_rows);
1010
0
            size_t idx = 0;
1011
0
            for (auto id = start_row_id; id < end_row_id; id++) {
1012
0
                if (before_index < _position_delete_ctx.index &&
1013
0
                    id == _position_delete_ctx.delete_rows[before_index]) {
1014
0
                    before_index++;
1015
0
                    continue;
1016
0
                }
1017
0
                _current_batch_row_ids[idx++] = (rowid_t)id;
1018
0
            }
1019
0
        }
1020
11
    } else {
1021
11
        if (batch_size < _remaining_rows) {
1022
10
            *read_rows = batch_size;
1023
10
            _remaining_rows -= batch_size;
1024
10
            *batch_eof = false;
1025
10
        } else {
1026
1
            *read_rows = _remaining_rows;
1027
1
            _remaining_rows = 0;
1028
1
            *batch_eof = true;
1029
1
        }
1030
11
        if (_need_current_batch_row_positions()) {
1031
0
            RETURN_IF_ERROR(_get_current_batch_row_id(*read_rows));
1032
0
        }
1033
11
    }
1034
11
    _total_read_rows += *read_rows;
1035
11
    return Status::OK();
1036
11
}
1037
1038
8
Status RowGroupReader::_get_current_batch_row_id(size_t read_rows) {
1039
8
    _current_batch_row_ids.clear();
1040
8
    _current_batch_row_ids.resize(read_rows);
1041
1042
8
    int64_t idx = 0;
1043
8
    int64_t read_range_rows = 0;
1044
25
    for (size_t range_idx = 0; range_idx < _read_ranges.range_size(); range_idx++) {
1045
17
        auto range = _read_ranges.get_range(range_idx);
1046
17
        if (read_rows == 0) {
1047
0
            break;
1048
0
        }
1049
17
        if (read_range_rows + (range.to() - range.from()) > _total_read_rows) {
1050
17
            int64_t fi =
1051
17
                    std::max(_total_read_rows, read_range_rows) - read_range_rows + range.from();
1052
17
            size_t len = std::min(read_rows, (size_t)(std::max(range.to(), fi) - fi));
1053
1054
17
            read_rows -= len;
1055
1056
40
            for (auto i = 0; i < len; i++) {
1057
23
                _current_batch_row_ids[idx++] =
1058
23
                        (rowid_t)(fi + i + _current_row_group_idx.first_row);
1059
23
            }
1060
17
        }
1061
17
        read_range_rows += range.to() - range.from();
1062
17
    }
1063
8
    return Status::OK();
1064
8
}
1065
1066
123
Status RowGroupReader::_build_pos_delete_filter(size_t read_rows) {
1067
123
    if (!_position_delete_ctx.has_filter) {
1068
123
        _pos_delete_filter_ptr.reset(nullptr);
1069
123
        _total_read_rows += read_rows;
1070
123
        return Status::OK();
1071
123
    }
1072
0
    _pos_delete_filter_ptr.reset(new IColumn::Filter(read_rows, 1));
1073
0
    auto* __restrict _pos_delete_filter_data = _pos_delete_filter_ptr->data();
1074
0
    while (_position_delete_ctx.index < _position_delete_ctx.end_index) {
1075
0
        const int64_t delete_row_index_in_row_group =
1076
0
                _position_delete_ctx.delete_rows[_position_delete_ctx.index] -
1077
0
                _position_delete_ctx.first_row_id;
1078
0
        int64_t read_range_rows = 0;
1079
0
        size_t remaining_read_rows = _total_read_rows + read_rows;
1080
0
        for (size_t range_idx = 0; range_idx < _read_ranges.range_size(); range_idx++) {
1081
0
            auto range = _read_ranges.get_range(range_idx);
1082
0
            if (delete_row_index_in_row_group < range.from()) {
1083
0
                ++_position_delete_ctx.index;
1084
0
                break;
1085
0
            } else if (delete_row_index_in_row_group < range.to()) {
1086
0
                int64_t index = (delete_row_index_in_row_group - range.from()) + read_range_rows -
1087
0
                                _total_read_rows;
1088
0
                if (index > read_rows - 1) {
1089
0
                    _total_read_rows += read_rows;
1090
0
                    return Status::OK();
1091
0
                }
1092
0
                _pos_delete_filter_data[index] = 0;
1093
0
                ++_position_delete_ctx.index;
1094
0
                break;
1095
0
            } else { // delete_row >= range.last_row
1096
0
            }
1097
1098
0
            int64_t range_size = range.to() - range.from();
1099
            // Don't search next range when there is no remaining_read_rows.
1100
0
            if (remaining_read_rows <= range_size) {
1101
0
                _total_read_rows += read_rows;
1102
0
                return Status::OK();
1103
0
            } else {
1104
0
                remaining_read_rows -= range_size;
1105
0
                read_range_rows += range_size;
1106
0
            }
1107
0
        }
1108
0
    }
1109
0
    _total_read_rows += read_rows;
1110
0
    return Status::OK();
1111
0
}
1112
1113
// need exception safety
1114
Status RowGroupReader::_filter_block(Block* block, int column_to_keep,
1115
89
                                     const std::vector<uint32_t>& columns_to_filter) {
1116
89
    if (_pos_delete_filter_ptr) {
1117
0
        RETURN_IF_CATCH_EXCEPTION(
1118
0
                Block::filter_block_internal(block, columns_to_filter, (*_pos_delete_filter_ptr)));
1119
0
    }
1120
89
    Block::erase_useless_column(block, column_to_keep);
1121
1122
89
    return Status::OK();
1123
89
}
1124
1125
4
Status RowGroupReader::_rewrite_dict_predicates() {
1126
4
    SCOPED_RAW_TIMER(&_dict_filter_rewrite_time);
1127
5
    for (auto it = _dict_filter_cols.begin(); it != _dict_filter_cols.end();) {
1128
1
        std::string& dict_filter_col_name = it->first;
1129
1
        int slot_id = it->second;
1130
        // 1. Get dictionary values to a string column.
1131
1
        MutableColumnPtr dict_value_column = ColumnString::create();
1132
1
        bool has_dict = false;
1133
1
        RETURN_IF_ERROR(_column_readers[dict_filter_col_name]->read_dict_values_to_column(
1134
1
                dict_value_column, &has_dict));
1135
1
#ifndef NDEBUG
1136
1
        dict_value_column->sanity_check();
1137
1
#endif
1138
1
        size_t dict_value_column_size = dict_value_column->size();
1139
1
        DCHECK(has_dict);
1140
        // 2. Build a temp block from the dict string column, then execute conjuncts and filter block.
1141
        // 2.1 Build a temp block from the dict string column to match the conjuncts executing.
1142
1
        Block temp_block;
1143
1
        int dict_pos = -1;
1144
1
        int index = 0;
1145
3
        for (const auto slot_desc : _tuple_descriptor->slots()) {
1146
3
            if (slot_desc->id() == slot_id) {
1147
1
                auto data_type = slot_desc->get_data_type_ptr();
1148
1
                if (data_type->is_nullable()) {
1149
0
                    temp_block.insert(
1150
0
                            {ColumnNullable::create(
1151
0
                                     std::move(
1152
0
                                             dict_value_column), // NOLINT(bugprone-use-after-move)
1153
0
                                     ColumnUInt8::create(dict_value_column_size, 0)),
1154
0
                             std::make_shared<DataTypeNullable>(std::make_shared<DataTypeString>()),
1155
0
                             ""});
1156
1
                } else {
1157
1
                    temp_block.insert(
1158
1
                            {std::move(dict_value_column), std::make_shared<DataTypeString>(), ""});
1159
1
                }
1160
1
                dict_pos = index;
1161
1162
2
            } else {
1163
2
                temp_block.insert(ColumnWithTypeAndName(slot_desc->get_empty_mutable_column(),
1164
2
                                                        slot_desc->get_data_type_ptr(),
1165
2
                                                        slot_desc->col_name()));
1166
2
            }
1167
3
            ++index;
1168
3
        }
1169
1170
        // 2.2 Execute conjuncts.
1171
1
        VExprContextSPtrs ctxs;
1172
1
        auto iter = _slot_id_to_filter_conjuncts->find(slot_id);
1173
1
        if (iter != _slot_id_to_filter_conjuncts->end()) {
1174
1
            for (auto& ctx : iter->second) {
1175
1
                ctxs.push_back(ctx);
1176
1
            }
1177
1
        } else {
1178
0
            std::stringstream msg;
1179
0
            msg << "_slot_id_to_filter_conjuncts: slot_id [" << slot_id << "] not found";
1180
0
            return Status::NotFound(msg.str());
1181
0
        }
1182
1183
1
        if (dict_pos != 0) {
1184
            // VExprContext.execute has an optimization, the filtering is executed when block->rows() > 0
1185
            // The following process may be tricky and time-consuming, but we have no other way.
1186
1
            temp_block.get_by_position(0).column->assert_mutable()->resize(dict_value_column_size);
1187
1
        }
1188
1
        IColumn::Filter result_filter(temp_block.rows(), 1);
1189
1
        bool can_filter_all;
1190
1
        {
1191
1
            RETURN_IF_ERROR(VExprContext::execute_conjuncts(ctxs, nullptr, &temp_block,
1192
1
                                                            &result_filter, &can_filter_all));
1193
1
        }
1194
1
        if (dict_pos != 0) {
1195
            // We have to clean the first column to insert right data.
1196
1
            temp_block.get_by_position(0).column->assert_mutable()->clear();
1197
1
        }
1198
1199
        // If can_filter_all = true, can filter this row group.
1200
1
        if (can_filter_all) {
1201
0
            _is_row_group_filtered = true;
1202
0
            return Status::OK();
1203
0
        }
1204
1205
        // 3. Get dict codes.
1206
1
        std::vector<int32_t> dict_codes;
1207
3
        for (size_t i = 0; i < result_filter.size(); ++i) {
1208
2
            if (result_filter[i]) {
1209
1
                dict_codes.emplace_back(i);
1210
1
            }
1211
2
        }
1212
1213
        // About Performance: if dict_column size is too large, it will generate a large IN filter.
1214
1
        if (dict_codes.size() > MAX_DICT_CODE_PREDICATE_TO_REWRITE) {
1215
0
            it = _dict_filter_cols.erase(it);
1216
0
            for (auto& ctx : ctxs) {
1217
0
                _filter_conjuncts.push_back(ctx);
1218
0
            }
1219
0
            continue;
1220
0
        }
1221
1222
        // 4. Rewrite conjuncts.
1223
1
        RETURN_IF_ERROR(_rewrite_dict_conjuncts(
1224
1
                dict_codes, slot_id, temp_block.get_by_position(dict_pos).column->is_nullable()));
1225
1
        ++it;
1226
1
    }
1227
4
    return Status::OK();
1228
4
}
1229
1230
Status RowGroupReader::_rewrite_dict_conjuncts(std::vector<int32_t>& dict_codes, int slot_id,
1231
1
                                               bool is_nullable) {
1232
1
    VExprSPtr root;
1233
1
    if (dict_codes.size() == 1) {
1234
1
        {
1235
1
            TFunction fn;
1236
1
            TFunctionName fn_name;
1237
1
            fn_name.__set_db_name("");
1238
1
            fn_name.__set_function_name("eq");
1239
1
            fn.__set_name(fn_name);
1240
1
            fn.__set_binary_type(TFunctionBinaryType::BUILTIN);
1241
1
            std::vector<TTypeDesc> arg_types;
1242
1
            arg_types.push_back(create_type_desc(PrimitiveType::TYPE_INT));
1243
1
            arg_types.push_back(create_type_desc(PrimitiveType::TYPE_INT));
1244
1
            fn.__set_arg_types(arg_types);
1245
1
            fn.__set_ret_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
1246
1
            fn.__set_has_var_args(false);
1247
1248
1
            TExprNode texpr_node;
1249
1
            texpr_node.__set_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
1250
1
            texpr_node.__set_node_type(TExprNodeType::BINARY_PRED);
1251
1
            texpr_node.__set_opcode(TExprOpcode::EQ);
1252
1
            texpr_node.__set_fn(fn);
1253
1
            texpr_node.__set_num_children(2);
1254
1
            texpr_node.__set_is_nullable(is_nullable);
1255
1
            root = VectorizedFnCall::create_shared(texpr_node);
1256
1
        }
1257
1
        {
1258
1
            SlotDescriptor* slot = nullptr;
1259
1
            const std::vector<SlotDescriptor*>& slots = _tuple_descriptor->slots();
1260
3
            for (auto each : slots) {
1261
3
                if (each->id() == slot_id) {
1262
1
                    slot = each;
1263
1
                    break;
1264
1
                }
1265
3
            }
1266
1
            root->add_child(VSlotRef::create_shared(slot));
1267
1
        }
1268
1
        {
1269
1
            TExprNode texpr_node;
1270
1
            texpr_node.__set_node_type(TExprNodeType::INT_LITERAL);
1271
1
            texpr_node.__set_type(create_type_desc(TYPE_INT));
1272
1
            TIntLiteral int_literal;
1273
1
            int_literal.__set_value(dict_codes[0]);
1274
1
            texpr_node.__set_int_literal(int_literal);
1275
1
            texpr_node.__set_is_nullable(is_nullable);
1276
1
            root->add_child(VLiteral::create_shared(texpr_node));
1277
1
        }
1278
1
    } else {
1279
0
        {
1280
0
            TTypeDesc type_desc = create_type_desc(PrimitiveType::TYPE_BOOLEAN);
1281
0
            TExprNode node;
1282
0
            node.__set_type(type_desc);
1283
0
            node.__set_node_type(TExprNodeType::IN_PRED);
1284
0
            node.in_predicate.__set_is_not_in(false);
1285
0
            node.__set_opcode(TExprOpcode::FILTER_IN);
1286
            // VdirectInPredicate assume is_nullable = false.
1287
0
            node.__set_is_nullable(false);
1288
1289
0
            std::shared_ptr<HybridSetBase> hybrid_set(
1290
0
                    create_set(PrimitiveType::TYPE_INT, dict_codes.size(), false));
1291
0
            for (int j = 0; j < dict_codes.size(); ++j) {
1292
0
                hybrid_set->insert(&dict_codes[j]);
1293
0
            }
1294
0
            root = VDirectInPredicate::create_shared(node, hybrid_set, false);
1295
0
        }
1296
0
        {
1297
0
            SlotDescriptor* slot = nullptr;
1298
0
            const std::vector<SlotDescriptor*>& slots = _tuple_descriptor->slots();
1299
0
            for (auto each : slots) {
1300
0
                if (each->id() == slot_id) {
1301
0
                    slot = each;
1302
0
                    break;
1303
0
                }
1304
0
            }
1305
0
            root->add_child(VSlotRef::create_shared(slot));
1306
0
        }
1307
0
    }
1308
1
    VExprContextSPtr rewritten_conjunct_ctx = VExprContext::create_shared(root);
1309
1
    RETURN_IF_ERROR(rewritten_conjunct_ctx->prepare(_state, *_row_descriptor));
1310
1
    RETURN_IF_ERROR(rewritten_conjunct_ctx->open(_state));
1311
1
    _dict_filter_conjuncts.push_back(rewritten_conjunct_ctx);
1312
1
    _filter_conjuncts.push_back(rewritten_conjunct_ctx);
1313
1
    return Status::OK();
1314
1
}
1315
1316
113
Status RowGroupReader::_convert_dict_cols_to_string_cols(Block* block) {
1317
113
    for (auto& dict_filter_cols : _dict_filter_cols) {
1318
1
        uint32_t block_pos = 0;
1319
1
        RETURN_IF_ERROR(_get_block_column_pos(*block, dict_filter_cols.first, &block_pos));
1320
1
        auto reader_iter = _column_readers.find(dict_filter_cols.first);
1321
1
        if (reader_iter == _column_readers.end() || reader_iter->second == nullptr) {
1322
0
            return Status::InternalError("Column reader for '{}' not found in parquet row group",
1323
0
                                         dict_filter_cols.first);
1324
0
        }
1325
1
        ColumnWithTypeAndName& column_with_type_and_name = block->get_by_position(block_pos);
1326
1
        const ColumnPtr& column = column_with_type_and_name.column;
1327
1
        if (const auto* nullable_column = check_and_get_column<ColumnNullable>(*column)) {
1328
0
            const ColumnPtr& nested_column = nullable_column->get_nested_column_ptr();
1329
0
            const auto* dict_column = assert_cast<const ColumnInt32*>(nested_column.get());
1330
0
            DCHECK(dict_column);
1331
1332
0
            auto string_column = DORIS_TRY(
1333
0
                    reader_iter->second->convert_dict_column_to_string_column(dict_column));
1334
1335
0
            column_with_type_and_name.type =
1336
0
                    std::make_shared<DataTypeNullable>(std::make_shared<DataTypeString>());
1337
0
            block->replace_by_position(
1338
0
                    block_pos, ColumnNullable::create(std::move(string_column),
1339
0
                                                      nullable_column->get_null_map_column_ptr()));
1340
1
        } else {
1341
1
            const auto* dict_column = assert_cast<const ColumnInt32*>(column.get());
1342
1
            auto string_column = DORIS_TRY(
1343
1
                    reader_iter->second->convert_dict_column_to_string_column(dict_column));
1344
1345
1
            column_with_type_and_name.type = std::make_shared<DataTypeString>();
1346
1
            block->replace_by_position(block_pos, std::move(string_column));
1347
1
        }
1348
1
    }
1349
113
    return Status::OK();
1350
113
}
1351
1352
74
ParquetColumnReader::ColumnStatistics RowGroupReader::merged_column_statistics() {
1353
74
    ParquetColumnReader::ColumnStatistics st;
1354
160
    for (auto& reader : _column_readers) {
1355
160
        auto ost = reader.second->column_statistics();
1356
160
        st.merge(ost);
1357
160
    }
1358
74
    return st;
1359
74
}
1360
1361
} // namespace doris