Coverage Report

Created: 2026-03-17 02:57

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