Coverage Report

Created: 2026-03-15 18:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/segment/column_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 "storage/segment/column_reader.h"
19
20
#include <assert.h>
21
#include <gen_cpp/Descriptors_types.h>
22
#include <gen_cpp/segment_v2.pb.h>
23
#include <glog/logging.h>
24
25
#include <algorithm>
26
#include <memory>
27
#include <ostream>
28
#include <set>
29
#include <utility>
30
31
#include "common/compiler_util.h" // IWYU pragma: keep
32
#include "common/status.h"
33
#include "core/assert_cast.h"
34
#include "core/binary_cast.hpp"
35
#include "core/column/column.h"
36
#include "core/column/column_array.h"
37
#include "core/column/column_map.h"
38
#include "core/column/column_nullable.h"
39
#include "core/column/column_struct.h"
40
#include "core/column/column_vector.h"
41
#include "core/data_type/data_type_agg_state.h"
42
#include "core/data_type/data_type_factory.hpp"
43
#include "core/data_type/data_type_nullable.h"
44
#include "core/data_type/define_primitive_type.h"
45
#include "core/decimal12.h"
46
#include "core/string_ref.h"
47
#include "core/types.h"
48
#include "core/value/decimalv2_value.h"
49
#include "core/value/vdatetime_value.h" //for VecDateTime
50
#include "io/fs/file_reader.h"
51
#include "storage/index/ann/ann_index_reader.h"
52
#include "storage/index/bloom_filter/bloom_filter.h"
53
#include "storage/index/bloom_filter/bloom_filter_index_reader.h"
54
#include "storage/index/index_file_reader.h"
55
#include "storage/index/index_reader.h"
56
#include "storage/index/inverted/analyzer/analyzer.h"
57
#include "storage/index/inverted/inverted_index_reader.h"
58
#include "storage/index/zone_map/zone_map_index.h"
59
#include "storage/iterators.h"
60
#include "storage/olap_common.h"
61
#include "storage/predicate/block_column_predicate.h"
62
#include "storage/predicate/column_predicate.h"
63
#include "storage/segment/binary_dict_page.h" // for BinaryDictPageDecoder
64
#include "storage/segment/binary_plain_page.h"
65
#include "storage/segment/column_meta_accessor.h"
66
#include "storage/segment/encoding_info.h" // for EncodingInfo
67
#include "storage/segment/page_decoder.h"
68
#include "storage/segment/page_handle.h" // for PageHandle
69
#include "storage/segment/page_io.h"
70
#include "storage/segment/page_pointer.h" // for PagePointer
71
#include "storage/segment/row_ranges.h"
72
#include "storage/segment/segment.h"
73
#include "storage/segment/segment_prefetcher.h"
74
#include "storage/segment/variant/variant_column_reader.h"
75
#include "storage/tablet/tablet_schema.h"
76
#include "storage/types.h" // for TypeInfo
77
#include "util/bitmap.h"
78
#include "util/block_compression.h"
79
#include "util/concurrency_stats.h"
80
#include "util/rle_encoding.h" // for RleDecoder
81
#include "util/slice.h"
82
83
namespace doris::segment_v2 {
84
#include "common/compile_check_begin.h"
85
#include "storage/segment/column_reader.h"
86
87
0
inline bool read_as_string(PrimitiveType type) {
88
0
    return type == PrimitiveType::TYPE_STRING || type == PrimitiveType::INVALID_TYPE ||
89
0
           type == PrimitiveType::TYPE_BITMAP || type == PrimitiveType::TYPE_FIXED_LENGTH_OBJECT;
90
0
}
91
92
Status ColumnReader::create_array(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
93
                                  const io::FileReaderSPtr& file_reader,
94
58
                                  std::shared_ptr<ColumnReader>* reader) {
95
58
    DCHECK(meta.children_columns_size() == 2 || meta.children_columns_size() == 3);
96
97
58
    std::shared_ptr<ColumnReader> item_reader;
98
58
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(0),
99
58
                                         meta.children_columns(0).num_rows(), file_reader,
100
58
                                         &item_reader));
101
102
58
    std::shared_ptr<ColumnReader> offset_reader;
103
58
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(1),
104
58
                                         meta.children_columns(1).num_rows(), file_reader,
105
58
                                         &offset_reader));
106
107
58
    std::shared_ptr<ColumnReader> null_reader;
108
58
    if (meta.is_nullable()) {
109
56
        RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(2),
110
56
                                             meta.children_columns(2).num_rows(), file_reader,
111
56
                                             &null_reader));
112
56
    }
113
114
    // The num rows of the array reader equals to the num rows of the length reader.
115
58
    uint64_t array_num_rows = meta.children_columns(1).num_rows();
116
58
    std::shared_ptr<ColumnReader> array_reader(
117
58
            new ColumnReader(opts, meta, array_num_rows, file_reader));
118
    //  array reader do not need to init
119
58
    array_reader->_sub_readers.resize(meta.children_columns_size());
120
58
    array_reader->_sub_readers[0] = std::move(item_reader);
121
58
    array_reader->_sub_readers[1] = std::move(offset_reader);
122
58
    if (meta.is_nullable()) {
123
56
        array_reader->_sub_readers[2] = std::move(null_reader);
124
56
    }
125
58
    array_reader->_meta_type = FieldType::OLAP_FIELD_TYPE_ARRAY;
126
58
    *reader = std::move(array_reader);
127
58
    return Status::OK();
128
58
}
129
130
Status ColumnReader::create_map(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
131
                                const io::FileReaderSPtr& file_reader,
132
494
                                std::shared_ptr<ColumnReader>* reader) {
133
    // map reader now has 3 sub readers for key, value, offsets(scalar), null(scala)
134
494
    DCHECK(meta.children_columns_size() == 3 || meta.children_columns_size() == 4);
135
494
    std::shared_ptr<ColumnReader> key_reader;
136
494
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(0),
137
494
                                         meta.children_columns(0).num_rows(), file_reader,
138
494
                                         &key_reader));
139
494
    std::shared_ptr<ColumnReader> val_reader;
140
494
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(1),
141
494
                                         meta.children_columns(1).num_rows(), file_reader,
142
494
                                         &val_reader));
143
494
    std::shared_ptr<ColumnReader> offset_reader;
144
494
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(2),
145
494
                                         meta.children_columns(2).num_rows(), file_reader,
146
494
                                         &offset_reader));
147
494
    std::shared_ptr<ColumnReader> null_reader;
148
494
    if (meta.is_nullable()) {
149
96
        RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(3),
150
96
                                             meta.children_columns(3).num_rows(), file_reader,
151
96
                                             &null_reader));
152
96
    }
153
154
    // The num rows of the map reader equals to the num rows of the length reader.
155
494
    uint64_t map_num_rows = meta.children_columns(2).num_rows();
156
494
    std::shared_ptr<ColumnReader> map_reader(
157
494
            new ColumnReader(opts, meta, map_num_rows, file_reader));
158
494
    map_reader->_sub_readers.resize(meta.children_columns_size());
159
160
494
    map_reader->_sub_readers[0] = std::move(key_reader);
161
494
    map_reader->_sub_readers[1] = std::move(val_reader);
162
494
    map_reader->_sub_readers[2] = std::move(offset_reader);
163
494
    if (meta.is_nullable()) {
164
96
        map_reader->_sub_readers[3] = std::move(null_reader);
165
96
    }
166
494
    map_reader->_meta_type = FieldType::OLAP_FIELD_TYPE_MAP;
167
494
    *reader = std::move(map_reader);
168
494
    return Status::OK();
169
494
}
170
171
Status ColumnReader::create_struct(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
172
                                   uint64_t num_rows, const io::FileReaderSPtr& file_reader,
173
0
                                   std::shared_ptr<ColumnReader>* reader) {
174
    // not support empty struct
175
0
    DCHECK(meta.children_columns_size() >= 1);
176
    // create struct column reader
177
0
    std::shared_ptr<ColumnReader> struct_reader(
178
0
            new ColumnReader(opts, meta, num_rows, file_reader));
179
0
    struct_reader->_sub_readers.reserve(meta.children_columns_size());
180
    // now we support struct column can add the children columns according to the schema-change behavior
181
0
    for (int i = 0; i < meta.children_columns_size(); i++) {
182
0
        std::shared_ptr<ColumnReader> sub_reader;
183
0
        RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(i),
184
0
                                             meta.children_columns(i).num_rows(), file_reader,
185
0
                                             &sub_reader));
186
0
        struct_reader->_sub_readers.push_back(std::move(sub_reader));
187
0
    }
188
0
    struct_reader->_meta_type = FieldType::OLAP_FIELD_TYPE_STRUCT;
189
0
    *reader = std::move(struct_reader);
190
0
    return Status::OK();
191
0
}
192
193
Status ColumnReader::create_agg_state(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
194
                                      uint64_t num_rows, const io::FileReaderSPtr& file_reader,
195
0
                                      std::shared_ptr<ColumnReader>* reader) {
196
0
    if (!meta.has_function_name()) { // meet old version ColumnMetaPB
197
0
        std::shared_ptr<ColumnReader> reader_local(
198
0
                new ColumnReader(opts, meta, num_rows, file_reader));
199
0
        RETURN_IF_ERROR(reader_local->init(&meta));
200
0
        *reader = std::move(reader_local);
201
0
        return Status::OK();
202
0
    }
203
204
0
    auto data_type = DataTypeFactory::instance().create_data_type(meta);
205
0
    const auto* agg_state_type = assert_cast<const DataTypeAggState*>(data_type.get());
206
0
    agg_state_type->check_function_compatibility(opts.be_exec_version);
207
0
    auto type = agg_state_type->get_serialized_type()->get_primitive_type();
208
209
0
    if (read_as_string(type)) {
210
0
        std::shared_ptr<ColumnReader> reader_local(
211
0
                new ColumnReader(opts, meta, num_rows, file_reader));
212
0
        RETURN_IF_ERROR(reader_local->init(&meta));
213
0
        *reader = std::move(reader_local);
214
0
        return Status::OK();
215
0
    } else if (type == PrimitiveType::TYPE_MAP) {
216
0
        return create_map(opts, meta, file_reader, reader);
217
0
    } else if (type == PrimitiveType::TYPE_ARRAY) {
218
0
        return create_array(opts, meta, file_reader, reader);
219
0
    } else if (type == PrimitiveType::TYPE_STRUCT) {
220
0
        return create_struct(opts, meta, num_rows, file_reader, reader);
221
0
    }
222
223
0
    return Status::InternalError("Not supported type: {}, serialized type: {}",
224
0
                                 agg_state_type->get_name(), int(type));
225
0
}
226
227
488
bool ColumnReader::is_compaction_reader_type(ReaderType type) {
228
488
    return type == ReaderType::READER_BASE_COMPACTION ||
229
488
           type == ReaderType::READER_CUMULATIVE_COMPACTION ||
230
488
           type == ReaderType::READER_COLD_DATA_COMPACTION ||
231
488
           type == ReaderType::READER_SEGMENT_COMPACTION ||
232
488
           type == ReaderType::READER_FULL_COMPACTION;
233
488
}
234
235
Status ColumnReader::create(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
236
                            uint64_t num_rows, const io::FileReaderSPtr& file_reader,
237
189k
                            std::shared_ptr<ColumnReader>* reader) {
238
189k
    if (is_scalar_type((FieldType)meta.type())) {
239
189k
        std::shared_ptr<ColumnReader> reader_local(
240
189k
                new ColumnReader(opts, meta, num_rows, file_reader));
241
189k
        RETURN_IF_ERROR(reader_local->init(&meta));
242
189k
        *reader = std::move(reader_local);
243
189k
        return Status::OK();
244
189k
    } else {
245
968
        auto type = (FieldType)meta.type();
246
968
        switch (type) {
247
0
        case FieldType::OLAP_FIELD_TYPE_AGG_STATE: {
248
0
            return create_agg_state(opts, meta, num_rows, file_reader, reader);
249
0
        }
250
0
        case FieldType::OLAP_FIELD_TYPE_STRUCT: {
251
0
            return create_struct(opts, meta, num_rows, file_reader, reader);
252
0
        }
253
58
        case FieldType::OLAP_FIELD_TYPE_ARRAY: {
254
58
            return create_array(opts, meta, file_reader, reader);
255
0
        }
256
494
        case FieldType::OLAP_FIELD_TYPE_MAP: {
257
494
            return create_map(opts, meta, file_reader, reader);
258
0
        }
259
375
        case FieldType::OLAP_FIELD_TYPE_VARIANT: {
260
            // Read variant only root data using a single ColumnReader
261
375
            std::shared_ptr<ColumnReader> reader_local(
262
375
                    new ColumnReader(opts, meta, num_rows, file_reader));
263
375
            RETURN_IF_ERROR(reader_local->init(&meta));
264
375
            *reader = std::move(reader_local);
265
375
            return Status::OK();
266
375
        }
267
0
        default:
268
0
            return Status::NotSupported("unsupported type for ColumnReader: {}",
269
0
                                        std::to_string(int(type)));
270
968
        }
271
968
    }
272
189k
}
273
274
404
ColumnReader::ColumnReader() = default;
275
276
ColumnReader::ColumnReader(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
277
                           uint64_t num_rows, io::FileReaderSPtr file_reader)
278
190k
        : _use_index_page_cache(!config::disable_storage_page_cache),
279
190k
          _opts(opts),
280
190k
          _num_rows(num_rows),
281
190k
          _file_reader(std::move(file_reader)),
282
190k
          _dict_encoding_type(UNKNOWN_DICT_ENCODING) {
283
190k
    _meta_length = meta.length();
284
190k
    _meta_type = (FieldType)meta.type();
285
190k
    if (_meta_type == FieldType::OLAP_FIELD_TYPE_ARRAY) {
286
58
        _meta_children_column_type = (FieldType)meta.children_columns(0).type();
287
58
    }
288
190k
    _data_type = DataTypeFactory::instance().create_data_type(meta);
289
190k
    _meta_is_nullable = meta.is_nullable();
290
190k
    _meta_dict_page = meta.dict_page();
291
190k
    _meta_compression = meta.compression();
292
190k
}
293
294
190k
ColumnReader::~ColumnReader() = default;
295
296
190k
int64_t ColumnReader::get_metadata_size() const {
297
190k
    return sizeof(ColumnReader) + (_segment_zone_map ? _segment_zone_map->ByteSizeLong() : 0);
298
190k
}
299
300
#ifdef BE_TEST
301
/// This function is only used in UT to verify the correctness of data read from zone map
302
/// See UT case 'SegCompactionMoWTest.SegCompactionInterleaveWithBig_ooooOOoOooooooooO'
303
/// be/test/olap/segcompaction_mow_test.cpp
304
void ColumnReader::check_data_by_zone_map_for_test(const MutableColumnPtr& dst) const {
305
    if (!_segment_zone_map) {
306
        return;
307
    }
308
309
    const auto rows = dst->size();
310
    if (rows == 0) {
311
        return;
312
    }
313
314
    FieldType type = _type_info->type();
315
316
    if (type != FieldType::OLAP_FIELD_TYPE_INT) {
317
        return;
318
    }
319
320
    auto* non_nullable_column =
321
            dst->is_nullable()
322
                    ? assert_cast<ColumnNullable*>(dst.get())->get_nested_column_ptr().get()
323
                    : dst.get();
324
325
    /// `PredicateColumnType<TYPE_INT>` does not support `void get(size_t n, Field& res)`,
326
    /// So here only check `CoumnVector<TYPE_INT>`
327
    if (check_and_get_column<ColumnVector<TYPE_INT>>(non_nullable_column) == nullptr) {
328
        return;
329
    }
330
331
    ZoneMap zone_map;
332
    THROW_IF_ERROR(ZoneMap::from_proto(*_segment_zone_map, _data_type, zone_map));
333
334
    if (zone_map.has_null) {
335
        return;
336
    }
337
338
    for (size_t i = 0; i != rows; ++i) {
339
        Field field;
340
        dst->get(i, field);
341
        DCHECK(!field.is_null());
342
        const auto v = field.get<TYPE_INT>();
343
        DCHECK_GE(v, zone_map.min_value.get<TYPE_INT>());
344
        DCHECK_LE(v, zone_map.max_value.get<TYPE_INT>());
345
    }
346
}
347
#endif
348
349
189k
Status ColumnReader::init(const ColumnMetaPB* meta) {
350
189k
    _type_info = get_type_info(meta);
351
352
189k
    if (meta->has_be_exec_version()) {
353
188k
        _be_exec_version = meta->be_exec_version();
354
188k
    }
355
356
189k
    if (_type_info == nullptr) {
357
0
        return Status::NotSupported("unsupported typeinfo, type={}", meta->type());
358
0
    }
359
189k
    RETURN_IF_ERROR(EncodingInfo::get(_type_info->type(), meta->encoding(), {}, &_encoding_info));
360
361
566k
    for (int i = 0; i < meta->indexes_size(); i++) {
362
376k
        const auto& index_meta = meta->indexes(i);
363
376k
        switch (index_meta.type()) {
364
0
        case BITMAP_INDEX:
365
0
            break;
366
189k
        case ORDINAL_INDEX:
367
189k
            _ordinal_index.reset(
368
189k
                    new OrdinalIndexReader(_file_reader, _num_rows, index_meta.ordinal_index()));
369
189k
            break;
370
186k
        case ZONE_MAP_INDEX:
371
186k
            _segment_zone_map =
372
186k
                    std::make_unique<ZoneMapPB>(index_meta.zone_map_index().segment_zone_map());
373
186k
            _zone_map_index.reset(new ZoneMapIndexReader(
374
186k
                    _file_reader, index_meta.zone_map_index().page_zone_maps()));
375
186k
            break;
376
4
        case BLOOM_FILTER_INDEX:
377
4
            _bloom_filter_index.reset(
378
4
                    new BloomFilterIndexReader(_file_reader, index_meta.bloom_filter_index()));
379
4
            break;
380
0
        case NESTED_OFFSETS_INDEX:
381
0
            break;
382
0
        default:
383
0
            return Status::Corruption("Bad file {}: invalid column index type {}",
384
0
                                      _file_reader->path().native(), index_meta.type());
385
376k
        }
386
376k
    }
387
189k
    update_metadata_size();
388
389
    // ArrayColumnWriter writes a single empty array and flushes. In this scenario,
390
    // the item writer doesn't write any data and the corresponding ordinal index is empty.
391
189k
    if (_ordinal_index == nullptr && !is_empty()) {
392
0
        return Status::Corruption("Bad file {}: missing ordinal index for column {}",
393
0
                                  _file_reader->path().native(), meta->column_id());
394
0
    }
395
396
189k
    return Status::OK();
397
189k
}
398
399
Status ColumnReader::new_index_iterator(const std::shared_ptr<IndexFileReader>& index_file_reader,
400
                                        const TabletIndex* index_meta,
401
2.58k
                                        std::unique_ptr<IndexIterator>* iterator) {
402
2.58k
    RETURN_IF_ERROR(_load_index(index_file_reader, index_meta));
403
2.58k
    {
404
2.58k
        std::shared_lock<std::shared_mutex> rlock(_load_index_lock);
405
2.58k
        auto iter = _index_readers.find(index_meta->index_id());
406
2.58k
        if (iter != _index_readers.end()) {
407
2.58k
            if (iter->second != nullptr) {
408
2.58k
                RETURN_IF_ERROR(iter->second->new_iterator(iterator));
409
2.58k
            }
410
2.58k
        }
411
2.58k
    }
412
2.58k
    return Status::OK();
413
2.58k
}
414
415
Status ColumnReader::read_page(const ColumnIteratorOptions& iter_opts, const PagePointer& pp,
416
                               PageHandle* handle, Slice* page_body, PageFooterPB* footer,
417
34.1k
                               BlockCompressionCodec* codec, bool is_dict_page) const {
418
34.1k
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().column_reader_read_page);
419
34.1k
    iter_opts.sanity_check();
420
34.1k
    PageReadOptions opts(iter_opts.io_ctx);
421
34.1k
    opts.verify_checksum = _opts.verify_checksum;
422
34.1k
    opts.use_page_cache = iter_opts.use_page_cache;
423
34.1k
    opts.kept_in_memory = _opts.kept_in_memory;
424
34.1k
    opts.type = iter_opts.type;
425
34.1k
    opts.file_reader = iter_opts.file_reader;
426
34.1k
    opts.page_pointer = pp;
427
34.1k
    opts.codec = codec;
428
34.1k
    opts.stats = iter_opts.stats;
429
34.1k
    opts.encoding_info = _encoding_info;
430
34.1k
    opts.is_dict_page = is_dict_page;
431
432
34.1k
    return PageIO::read_and_decompress_page(opts, handle, page_body, footer);
433
34.1k
}
434
435
Status ColumnReader::get_row_ranges_by_zone_map(
436
        const AndBlockColumnPredicate* col_predicates,
437
        const std::vector<std::shared_ptr<const ColumnPredicate>>* delete_predicates,
438
552
        RowRanges* row_ranges, const ColumnIteratorOptions& iter_opts) {
439
552
    std::vector<uint32_t> page_indexes;
440
552
    RETURN_IF_ERROR(
441
552
            _get_filtered_pages(col_predicates, delete_predicates, &page_indexes, iter_opts));
442
552
    RETURN_IF_ERROR(_calculate_row_ranges(page_indexes, row_ranges, iter_opts));
443
552
    return Status::OK();
444
552
}
445
446
1.61k
Status ColumnReader::next_batch_of_zone_map(size_t* n, MutableColumnPtr& dst) const {
447
1.61k
    if (_segment_zone_map == nullptr) {
448
0
        return Status::InternalError("segment zonemap not exist");
449
0
    }
450
    // TODO: this work to get min/max value seems should only do once
451
1.61k
    ZoneMap zone_map;
452
1.61k
    RETURN_IF_ERROR(ZoneMap::from_proto(*_segment_zone_map, _data_type, zone_map));
453
454
1.61k
    dst->reserve(*n);
455
1.61k
    if (!zone_map.has_not_null) {
456
0
        assert_cast<ColumnNullable&>(*dst).insert_many_defaults(*n);
457
0
        return Status::OK();
458
0
    }
459
1.61k
    dst->insert(zone_map.max_value);
460
3.31k
    for (int i = 1; i < *n; ++i) {
461
1.70k
        dst->insert(zone_map.min_value);
462
1.70k
    }
463
1.61k
    return Status::OK();
464
1.61k
}
465
466
Status ColumnReader::match_condition(const AndBlockColumnPredicate* col_predicates,
467
11.5k
                                     bool* matched) const {
468
11.5k
    *matched = true;
469
11.5k
    if (_zone_map_index == nullptr) {
470
0
        return Status::OK();
471
0
    }
472
11.5k
    ZoneMap zone_map;
473
11.5k
    RETURN_IF_ERROR(ZoneMap::from_proto(*_segment_zone_map, _data_type, zone_map));
474
475
11.5k
    *matched = _zone_map_match_condition(zone_map, col_predicates);
476
11.5k
    return Status::OK();
477
11.5k
}
478
479
Status ColumnReader::prune_predicates_by_zone_map(
480
        std::vector<std::shared_ptr<ColumnPredicate>>& predicates, const int column_id,
481
41.8k
        bool* pruned) const {
482
41.8k
    *pruned = false;
483
41.8k
    if (_zone_map_index == nullptr) {
484
0
        return Status::OK();
485
0
    }
486
487
41.8k
    ZoneMap zone_map;
488
41.8k
    RETURN_IF_ERROR(ZoneMap::from_proto(*_segment_zone_map, _data_type, zone_map));
489
41.8k
    if (zone_map.pass_all) {
490
0
        return Status::OK();
491
0
    }
492
493
84.2k
    for (auto it = predicates.begin(); it != predicates.end();) {
494
42.4k
        auto predicate = *it;
495
42.4k
        if (predicate->column_id() == column_id && predicate->is_always_true(zone_map)) {
496
0
            *pruned = true;
497
0
            it = predicates.erase(it);
498
42.4k
        } else {
499
42.4k
            ++it;
500
42.4k
        }
501
42.4k
    }
502
41.8k
    return Status::OK();
503
41.8k
}
504
505
bool ColumnReader::_zone_map_match_condition(const ZoneMap& zone_map,
506
11.8k
                                             const AndBlockColumnPredicate* col_predicates) const {
507
11.8k
    if (zone_map.pass_all) {
508
0
        return true;
509
0
    }
510
511
11.8k
    return col_predicates->evaluate_and(zone_map);
512
11.8k
}
513
514
Status ColumnReader::_get_filtered_pages(
515
        const AndBlockColumnPredicate* col_predicates,
516
        const std::vector<std::shared_ptr<const ColumnPredicate>>* delete_predicates,
517
552
        std::vector<uint32_t>* page_indexes, const ColumnIteratorOptions& iter_opts) {
518
552
    RETURN_IF_ERROR(_load_zone_map_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
519
520
552
    const std::vector<ZoneMapPB>& zone_maps = _zone_map_index->page_zone_maps();
521
552
    size_t page_size = _zone_map_index->num_pages();
522
1.10k
    for (size_t i = 0; i < page_size; ++i) {
523
550
        if (zone_maps[i].pass_all()) {
524
282
            page_indexes->push_back(cast_set<uint32_t>(i));
525
282
        } else {
526
268
            segment_v2::ZoneMap zone_map;
527
268
            RETURN_IF_ERROR(ZoneMap::from_proto(zone_maps[i], _data_type, zone_map));
528
268
            if (_zone_map_match_condition(zone_map, col_predicates)) {
529
268
                bool should_read = true;
530
268
                if (delete_predicates != nullptr) {
531
0
                    for (auto del_pred : *delete_predicates) {
532
                        // TODO: Both `min_value` and `max_value` should be 0 or neither should be 0.
533
                        //  So nullable only need to judge once.
534
0
                        if (del_pred->evaluate_del(zone_map)) {
535
0
                            should_read = false;
536
0
                            break;
537
0
                        }
538
0
                    }
539
0
                }
540
268
                if (should_read) {
541
268
                    page_indexes->push_back(cast_set<uint32_t>(i));
542
268
                }
543
268
            }
544
268
        }
545
550
    }
546
552
    VLOG(1) << "total-pages: " << page_size << " not-filtered-pages: " << page_indexes->size()
547
4
            << " filtered-percent:"
548
4
            << 1.0 - (static_cast<double>(page_indexes->size()) /
549
4
                      (static_cast<double>(page_size) * 1.0));
550
552
    return Status::OK();
551
552
}
552
553
Status ColumnReader::_calculate_row_ranges(const std::vector<uint32_t>& page_indexes,
554
                                           RowRanges* row_ranges,
555
546
                                           const ColumnIteratorOptions& iter_opts) {
556
546
    row_ranges->clear();
557
546
    RETURN_IF_ERROR(_load_ordinal_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
558
552
    for (auto i : page_indexes) {
559
552
        ordinal_t page_first_id = _ordinal_index->get_first_ordinal(i);
560
552
        ordinal_t page_last_id = _ordinal_index->get_last_ordinal(i);
561
552
        RowRanges page_row_ranges(RowRanges::create_single(page_first_id, page_last_id + 1));
562
552
        RowRanges::ranges_union(*row_ranges, page_row_ranges, row_ranges);
563
552
    }
564
546
    return Status::OK();
565
546
}
566
567
Status ColumnReader::get_row_ranges_by_bloom_filter(const AndBlockColumnPredicate* col_predicates,
568
                                                    RowRanges* row_ranges,
569
0
                                                    const ColumnIteratorOptions& iter_opts) {
570
0
    RETURN_IF_ERROR(_load_ordinal_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
571
0
    RETURN_IF_ERROR(
572
0
            _load_bloom_filter_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
573
0
    RowRanges bf_row_ranges;
574
0
    std::unique_ptr<BloomFilterIndexIterator> bf_iter;
575
0
    RETURN_IF_ERROR(_bloom_filter_index->new_iterator(&bf_iter, iter_opts.stats));
576
0
    size_t range_size = row_ranges->range_size();
577
    // get covered page ids
578
0
    std::set<uint32_t> page_ids;
579
0
    for (int i = 0; i < range_size; ++i) {
580
0
        int64_t from = row_ranges->get_range_from(i);
581
0
        int64_t idx = from;
582
0
        int64_t to = row_ranges->get_range_to(i);
583
0
        auto iter = _ordinal_index->seek_at_or_before(from);
584
0
        while (idx < to && iter.valid()) {
585
0
            page_ids.insert(iter.page_index());
586
0
            idx = iter.last_ordinal() + 1;
587
0
            iter.next();
588
0
        }
589
0
    }
590
0
    for (auto& pid : page_ids) {
591
0
        std::unique_ptr<BloomFilter> bf;
592
0
        RETURN_IF_ERROR(bf_iter->read_bloom_filter(pid, &bf));
593
0
        if (col_predicates->evaluate_and(bf.get())) {
594
0
            bf_row_ranges.add(RowRange(_ordinal_index->get_first_ordinal(pid),
595
0
                                       _ordinal_index->get_last_ordinal(pid) + 1));
596
0
        }
597
0
    }
598
0
    RowRanges::ranges_intersection(*row_ranges, bf_row_ranges, row_ranges);
599
0
    return Status::OK();
600
0
}
601
602
Status ColumnReader::_load_ordinal_index(bool use_page_cache, bool kept_in_memory,
603
24.7k
                                         const ColumnIteratorOptions& iter_opts) {
604
24.7k
    if (!_ordinal_index) {
605
0
        return Status::InternalError("ordinal_index not inited");
606
0
    }
607
24.7k
    return _ordinal_index->load(use_page_cache, kept_in_memory, iter_opts.stats);
608
24.7k
}
609
610
Status ColumnReader::_load_zone_map_index(bool use_page_cache, bool kept_in_memory,
611
552
                                          const ColumnIteratorOptions& iter_opts) {
612
552
    if (_zone_map_index != nullptr) {
613
550
        return _zone_map_index->load(use_page_cache, kept_in_memory, iter_opts.stats);
614
550
    }
615
2
    return Status::OK();
616
552
}
617
618
Status ColumnReader::_load_index(const std::shared_ptr<IndexFileReader>& index_file_reader,
619
2.58k
                                 const TabletIndex* index_meta) {
620
2.58k
    std::unique_lock<std::shared_mutex> wlock(_load_index_lock);
621
622
2.58k
    if (index_meta == nullptr) {
623
0
        return Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
624
0
                "Failed to load inverted index: index metadata is null");
625
0
    }
626
627
2.58k
    auto it = _index_readers.find(index_meta->index_id());
628
2.58k
    if (it != _index_readers.end()) {
629
0
        return Status::OK();
630
0
    }
631
632
2.58k
    bool should_analyzer =
633
2.58k
            inverted_index::InvertedIndexAnalyzer::should_analyzer(index_meta->properties());
634
635
2.58k
    FieldType type;
636
2.58k
    if (_meta_type == FieldType::OLAP_FIELD_TYPE_ARRAY) {
637
2
        type = _meta_children_column_type;
638
2.57k
    } else {
639
2.57k
        type = _type_info->type();
640
2.57k
    }
641
642
2.58k
    if (index_meta->index_type() == IndexType::ANN) {
643
1
        _index_readers[index_meta->index_id()] =
644
1
                std::make_shared<AnnIndexReader>(index_meta, index_file_reader);
645
1
        return Status::OK();
646
1
    }
647
648
2.58k
    IndexReaderPtr index_reader;
649
650
2.58k
    if (is_string_type(type)) {
651
2.17k
        if (should_analyzer) {
652
1.70k
            try {
653
1.70k
                index_reader = FullTextIndexReader::create_shared(index_meta, index_file_reader);
654
1.70k
            } catch (const CLuceneError& e) {
655
0
                return Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
656
0
                        "create FullTextIndexReader error: {}", e.what());
657
0
            }
658
1.70k
        } else {
659
476
            try {
660
476
                index_reader =
661
476
                        StringTypeInvertedIndexReader::create_shared(index_meta, index_file_reader);
662
476
            } catch (const CLuceneError& e) {
663
0
                return Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
664
0
                        "create StringTypeInvertedIndexReader error: {}", e.what());
665
0
            }
666
476
        }
667
2.17k
    } else if (is_numeric_type(type)) {
668
402
        try {
669
402
            index_reader = BkdIndexReader::create_shared(index_meta, index_file_reader);
670
402
        } catch (const CLuceneError& e) {
671
0
            return Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
672
0
                    "create BkdIndexReader error: {}", e.what());
673
0
        }
674
402
    } else {
675
0
        return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
676
0
                "Field type {} is not supported for inverted index", type);
677
0
    }
678
2.58k
    _index_readers[index_meta->index_id()] = index_reader;
679
2.58k
    return Status::OK();
680
2.58k
}
681
682
552
bool ColumnReader::has_bloom_filter_index(bool ngram) const {
683
552
    if (_bloom_filter_index == nullptr) return false;
684
685
0
    if (ngram) {
686
0
        return _bloom_filter_index->algorithm() == BloomFilterAlgorithmPB::NGRAM_BLOOM_FILTER;
687
0
    } else {
688
0
        return _bloom_filter_index->algorithm() != BloomFilterAlgorithmPB::NGRAM_BLOOM_FILTER;
689
0
    }
690
0
}
691
692
Status ColumnReader::_load_bloom_filter_index(bool use_page_cache, bool kept_in_memory,
693
0
                                              const ColumnIteratorOptions& iter_opts) {
694
0
    if (_bloom_filter_index != nullptr) {
695
0
        return _bloom_filter_index->load(use_page_cache, kept_in_memory, iter_opts.stats);
696
0
    }
697
0
    return Status::OK();
698
0
}
699
700
Status ColumnReader::seek_at_or_before(ordinal_t ordinal, OrdinalPageIndexIterator* iter,
701
24.1k
                                       const ColumnIteratorOptions& iter_opts) {
702
24.1k
    RETURN_IF_ERROR(_load_ordinal_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
703
24.1k
    *iter = _ordinal_index->seek_at_or_before(ordinal);
704
24.1k
    if (!iter->valid()) {
705
0
        return Status::NotFound("Failed to seek to ordinal {}, ", ordinal);
706
0
    }
707
24.1k
    return Status::OK();
708
24.1k
}
709
710
Status ColumnReader::get_ordinal_index_reader(OrdinalIndexReader*& reader,
711
0
                                              OlapReaderStatistics* index_load_stats) {
712
0
    CHECK(_ordinal_index) << fmt::format("ordinal index is null for column reader of type {}",
713
0
                                         std::to_string(int(_meta_type)));
714
0
    RETURN_IF_ERROR(
715
0
            _ordinal_index->load(_use_index_page_cache, _opts.kept_in_memory, index_load_stats));
716
0
    reader = _ordinal_index.get();
717
0
    return Status::OK();
718
0
}
719
720
1.65k
Status ColumnReader::new_iterator(ColumnIteratorUPtr* iterator, const TabletColumn* tablet_column) {
721
1.65k
    return new_iterator(iterator, tablet_column, nullptr);
722
1.65k
}
723
724
Status ColumnReader::new_iterator(ColumnIteratorUPtr* iterator, const TabletColumn* tablet_column,
725
187k
                                  const StorageReadOptions* opt) {
726
187k
    if (is_empty()) {
727
90
        *iterator = std::make_unique<EmptyFileColumnIterator>();
728
90
        return Status::OK();
729
90
    }
730
187k
    if (is_scalar_type(_meta_type)) {
731
187k
        *iterator = std::make_unique<FileColumnIterator>(shared_from_this());
732
187k
        (*iterator)->set_column_name(tablet_column ? tablet_column->name() : "");
733
187k
        return Status::OK();
734
187k
    } else {
735
396
        auto type = _meta_type;
736
396
        switch (type) {
737
0
        case FieldType::OLAP_FIELD_TYPE_AGG_STATE: {
738
0
            return new_agg_state_iterator(iterator);
739
0
        }
740
0
        case FieldType::OLAP_FIELD_TYPE_STRUCT: {
741
0
            return new_struct_iterator(iterator, tablet_column);
742
0
        }
743
58
        case FieldType::OLAP_FIELD_TYPE_ARRAY: {
744
58
            return new_array_iterator(iterator, tablet_column);
745
0
        }
746
282
        case FieldType::OLAP_FIELD_TYPE_MAP: {
747
282
            return new_map_iterator(iterator, tablet_column);
748
0
        }
749
0
        default:
750
0
            return Status::NotSupported("unsupported type to create iterator: {}",
751
0
                                        std::to_string(int(type)));
752
396
        }
753
396
    }
754
187k
}
755
756
0
Status ColumnReader::new_agg_state_iterator(ColumnIteratorUPtr* iterator) {
757
0
    *iterator = std::make_unique<FileColumnIterator>(shared_from_this());
758
0
    return Status::OK();
759
0
}
760
761
Status ColumnReader::new_array_iterator(ColumnIteratorUPtr* iterator,
762
58
                                        const TabletColumn* tablet_column) {
763
58
    ColumnIteratorUPtr item_iterator;
764
58
    RETURN_IF_ERROR(_sub_readers[0]->new_iterator(
765
58
            &item_iterator, tablet_column && tablet_column->get_subtype_count() > 0
766
58
                                    ? &tablet_column->get_sub_column(0)
767
58
                                    : nullptr));
768
769
58
    item_iterator->set_column_name(tablet_column ? tablet_column->get_sub_column(0).name() : "");
770
771
58
    ColumnIteratorUPtr offset_iterator;
772
58
    RETURN_IF_ERROR(_sub_readers[1]->new_iterator(&offset_iterator, nullptr));
773
58
    auto* file_iter = static_cast<FileColumnIterator*>(offset_iterator.release());
774
58
    OffsetFileColumnIteratorUPtr ofcIter = std::make_unique<OffsetFileColumnIterator>(
775
58
            std::unique_ptr<FileColumnIterator>(file_iter));
776
777
58
    ColumnIteratorUPtr null_iterator;
778
58
    if (is_nullable()) {
779
56
        RETURN_IF_ERROR(_sub_readers[2]->new_iterator(&null_iterator, nullptr));
780
56
    }
781
58
    *iterator = std::make_unique<ArrayFileColumnIterator>(shared_from_this(), std::move(ofcIter),
782
58
                                                          std::move(item_iterator),
783
58
                                                          std::move(null_iterator));
784
58
    return Status::OK();
785
58
}
786
787
Status ColumnReader::new_map_iterator(ColumnIteratorUPtr* iterator,
788
282
                                      const TabletColumn* tablet_column) {
789
282
    ColumnIteratorUPtr key_iterator;
790
282
    RETURN_IF_ERROR(_sub_readers[0]->new_iterator(
791
282
            &key_iterator, tablet_column && tablet_column->get_subtype_count() > 1
792
282
                                   ? &tablet_column->get_sub_column(0)
793
282
                                   : nullptr));
794
282
    key_iterator->set_column_name(tablet_column ? tablet_column->get_sub_column(0).name() : "");
795
282
    ColumnIteratorUPtr val_iterator;
796
282
    RETURN_IF_ERROR(_sub_readers[1]->new_iterator(
797
282
            &val_iterator, tablet_column && tablet_column->get_subtype_count() > 1
798
282
                                   ? &tablet_column->get_sub_column(1)
799
282
                                   : nullptr));
800
282
    val_iterator->set_column_name(tablet_column ? tablet_column->get_sub_column(1).name() : "");
801
282
    ColumnIteratorUPtr offsets_iterator;
802
282
    RETURN_IF_ERROR(_sub_readers[2]->new_iterator(&offsets_iterator, nullptr));
803
282
    auto* file_iter = static_cast<FileColumnIterator*>(offsets_iterator.release());
804
282
    OffsetFileColumnIteratorUPtr ofcIter = std::make_unique<OffsetFileColumnIterator>(
805
282
            std::unique_ptr<FileColumnIterator>(file_iter));
806
807
282
    ColumnIteratorUPtr null_iterator;
808
282
    if (is_nullable()) {
809
96
        RETURN_IF_ERROR(_sub_readers[3]->new_iterator(&null_iterator, nullptr));
810
96
    }
811
282
    *iterator = std::make_unique<MapFileColumnIterator>(
812
282
            shared_from_this(), std::move(null_iterator), std::move(ofcIter),
813
282
            std::move(key_iterator), std::move(val_iterator));
814
282
    return Status::OK();
815
282
}
816
817
Status ColumnReader::new_struct_iterator(ColumnIteratorUPtr* iterator,
818
0
                                         const TabletColumn* tablet_column) {
819
0
    std::vector<ColumnIteratorUPtr> sub_column_iterators;
820
0
    size_t child_size = is_nullable() ? _sub_readers.size() - 1 : _sub_readers.size();
821
0
    size_t tablet_column_size = tablet_column ? tablet_column->get_sub_columns().size() : 0;
822
0
    sub_column_iterators.reserve(child_size);
823
824
0
    for (uint64_t i = 0; i < child_size; i++) {
825
0
        ColumnIteratorUPtr sub_column_iterator;
826
0
        RETURN_IF_ERROR(_sub_readers[i]->new_iterator(
827
0
                &sub_column_iterator, tablet_column ? &tablet_column->get_sub_column(i) : nullptr));
828
0
        sub_column_iterator->set_column_name(tablet_column ? tablet_column->get_sub_column(i).name()
829
0
                                                           : "");
830
0
        sub_column_iterators.emplace_back(std::move(sub_column_iterator));
831
0
    }
832
833
    // create default_iterator for schema-change behavior which increase column
834
0
    for (size_t i = child_size; i < tablet_column_size; i++) {
835
0
        TabletColumn column = tablet_column->get_sub_column(i);
836
0
        ColumnIteratorUPtr it;
837
0
        RETURN_IF_ERROR(Segment::new_default_iterator(column, &it));
838
0
        it->set_column_name(column.name());
839
0
        sub_column_iterators.emplace_back(std::move(it));
840
0
    }
841
842
0
    ColumnIteratorUPtr null_iterator;
843
0
    if (is_nullable()) {
844
0
        RETURN_IF_ERROR(_sub_readers[child_size]->new_iterator(&null_iterator, nullptr));
845
0
    }
846
0
    *iterator = std::make_unique<StructFileColumnIterator>(
847
0
            shared_from_this(), std::move(null_iterator), std::move(sub_column_iterators));
848
0
    return Status::OK();
849
0
}
850
851
Result<TColumnAccessPaths> ColumnIterator::_get_sub_access_paths(
852
12
        const TColumnAccessPaths& access_paths) {
853
12
    TColumnAccessPaths sub_access_paths = access_paths;
854
19
    for (auto it = sub_access_paths.begin(); it != sub_access_paths.end();) {
855
9
        TColumnAccessPath& name_path = *it;
856
9
        if (name_path.data_access_path.path.empty()) {
857
1
            return ResultError(
858
1
                    Status::InternalError("Invalid access path for struct column: path is empty"));
859
1
        }
860
861
8
        if (!StringCaseEqual()(name_path.data_access_path.path[0], _column_name)) {
862
1
            return ResultError(Status::InternalError(
863
1
                    R"(Invalid access path for column: expected name "{}", got "{}")", _column_name,
864
1
                    name_path.data_access_path.path[0]));
865
1
        }
866
867
7
        name_path.data_access_path.path.erase(name_path.data_access_path.path.begin());
868
7
        if (!name_path.data_access_path.path.empty()) {
869
6
            ++it;
870
6
        } else {
871
1
            set_need_to_read();
872
1
            it = sub_access_paths.erase(it);
873
1
        }
874
7
    }
875
10
    return sub_access_paths;
876
12
}
877
878
///====================== MapFileColumnIterator ============================////
879
MapFileColumnIterator::MapFileColumnIterator(std::shared_ptr<ColumnReader> reader,
880
                                             ColumnIteratorUPtr null_iterator,
881
                                             OffsetFileColumnIteratorUPtr offsets_iterator,
882
                                             ColumnIteratorUPtr key_iterator,
883
                                             ColumnIteratorUPtr val_iterator)
884
284
        : _map_reader(reader),
885
284
          _offsets_iterator(std::move(offsets_iterator)),
886
284
          _key_iterator(std::move(key_iterator)),
887
284
          _val_iterator(std::move(val_iterator)) {
888
284
    if (_map_reader->is_nullable()) {
889
96
        _null_iterator = std::move(null_iterator);
890
96
    }
891
284
}
892
893
278
Status MapFileColumnIterator::init(const ColumnIteratorOptions& opts) {
894
278
    if (_reading_flag == ReadingFlag::SKIP_READING) {
895
0
        DLOG(INFO) << "Map column iterator column " << _column_name << " skip reading.";
896
0
        return Status::OK();
897
0
    }
898
278
    RETURN_IF_ERROR(_key_iterator->init(opts));
899
278
    RETURN_IF_ERROR(_val_iterator->init(opts));
900
278
    RETURN_IF_ERROR(_offsets_iterator->init(opts));
901
278
    if (_map_reader->is_nullable()) {
902
96
        RETURN_IF_ERROR(_null_iterator->init(opts));
903
96
    }
904
278
    return Status::OK();
905
278
}
906
907
294
Status MapFileColumnIterator::seek_to_ordinal(ordinal_t ord) {
908
294
    if (_reading_flag == ReadingFlag::SKIP_READING) {
909
0
        DLOG(INFO) << "Map column iterator column " << _column_name << " skip reading.";
910
0
        return Status::OK();
911
0
    }
912
913
294
    if (_map_reader->is_nullable()) {
914
112
        RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
915
112
    }
916
294
    RETURN_IF_ERROR(_offsets_iterator->seek_to_ordinal(ord));
917
    // here to use offset info
918
294
    ordinal_t offset = 0;
919
294
    RETURN_IF_ERROR(_offsets_iterator->_peek_one_offset(&offset));
920
294
    RETURN_IF_ERROR(_key_iterator->seek_to_ordinal(offset));
921
294
    RETURN_IF_ERROR(_val_iterator->seek_to_ordinal(offset));
922
294
    return Status::OK();
923
294
}
924
925
0
Status MapFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
926
0
    RETURN_IF_ERROR(_offsets_iterator->init_prefetcher(params));
927
0
    if (_map_reader->is_nullable()) {
928
0
        RETURN_IF_ERROR(_null_iterator->init_prefetcher(params));
929
0
    }
930
0
    RETURN_IF_ERROR(_key_iterator->init_prefetcher(params));
931
0
    RETURN_IF_ERROR(_val_iterator->init_prefetcher(params));
932
0
    return Status::OK();
933
0
}
934
935
void MapFileColumnIterator::collect_prefetchers(
936
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
937
0
        PrefetcherInitMethod init_method) {
938
0
    _offsets_iterator->collect_prefetchers(prefetchers, init_method);
939
0
    if (_map_reader->is_nullable()) {
940
0
        _null_iterator->collect_prefetchers(prefetchers, init_method);
941
0
    }
942
    // the actual data pages to read of key/value column depends on the read result of offset column,
943
    // so we can't init prefetch blocks according to rowids, just prefetch all data blocks here.
944
0
    _key_iterator->collect_prefetchers(prefetchers, PrefetcherInitMethod::ALL_DATA_BLOCKS);
945
0
    _val_iterator->collect_prefetchers(prefetchers, PrefetcherInitMethod::ALL_DATA_BLOCKS);
946
0
}
947
948
293
Status MapFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
949
293
    if (_reading_flag == ReadingFlag::SKIP_READING) {
950
0
        DLOG(INFO) << "Map column iterator column " << _column_name << " skip reading.";
951
0
        dst->insert_many_defaults(*n);
952
0
        return Status::OK();
953
0
    }
954
955
293
    auto& column_map = assert_cast<ColumnMap&, TypeCheckOnRelease::DISABLE>(
956
293
            dst->is_nullable() ? static_cast<ColumnNullable&>(*dst).get_nested_column() : *dst);
957
293
    auto column_offsets_ptr = column_map.get_offsets_column().assume_mutable();
958
293
    bool offsets_has_null = false;
959
293
    ssize_t start = column_offsets_ptr->size();
960
293
    RETURN_IF_ERROR(_offsets_iterator->next_batch(n, column_offsets_ptr, &offsets_has_null));
961
293
    if (*n == 0) {
962
0
        return Status::OK();
963
0
    }
964
293
    auto& column_offsets = static_cast<ColumnArray::ColumnOffsets&>(*column_offsets_ptr);
965
293
    RETURN_IF_ERROR(_offsets_iterator->_calculate_offsets(start, column_offsets));
966
293
    DCHECK(column_offsets.get_data().back() >= column_offsets.get_data()[start - 1]);
967
293
    size_t num_items =
968
293
            column_offsets.get_data().back() - column_offsets.get_data()[start - 1]; // -1 is valid
969
293
    auto key_ptr = column_map.get_keys().assume_mutable();
970
293
    auto val_ptr = column_map.get_values().assume_mutable();
971
972
293
    if (num_items > 0) {
973
261
        size_t num_read = num_items;
974
261
        bool key_has_null = false;
975
261
        bool val_has_null = false;
976
261
        RETURN_IF_ERROR(_key_iterator->next_batch(&num_read, key_ptr, &key_has_null));
977
261
        RETURN_IF_ERROR(_val_iterator->next_batch(&num_read, val_ptr, &val_has_null));
978
261
        DCHECK(num_read == num_items);
979
980
261
        column_map.get_keys_ptr() = std::move(key_ptr);
981
261
        column_map.get_values_ptr() = std::move(val_ptr);
982
261
    }
983
984
293
    if (dst->is_nullable()) {
985
112
        size_t num_read = *n;
986
112
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
987
        // in not-null to null linked-schemachange mode,
988
        // actually we do not change dat data include meta in footer,
989
        // so may dst from changed meta which is nullable but old data is not nullable,
990
        // if so, we should set null_map to all null by default
991
112
        if (_null_iterator) {
992
112
            bool null_signs_has_null = false;
993
112
            RETURN_IF_ERROR(
994
112
                    _null_iterator->next_batch(&num_read, null_map_ptr, &null_signs_has_null));
995
112
        } else {
996
0
            auto& null_map = assert_cast<ColumnUInt8&, TypeCheckOnRelease::DISABLE>(*null_map_ptr);
997
0
            null_map.insert_many_vals(0, num_read);
998
0
        }
999
112
        DCHECK(num_read == *n);
1000
112
    }
1001
293
    return Status::OK();
1002
293
}
1003
1004
Status MapFileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
1005
13
                                             MutableColumnPtr& dst) {
1006
13
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1007
1
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
1008
1
        dst->insert_many_defaults(count);
1009
1
        return Status::OK();
1010
1
    }
1011
12
    if (count == 0) {
1012
0
        return Status::OK();
1013
0
    }
1014
    // resolve ColumnMap and nullable wrapper
1015
12
    const auto* column_map = check_and_get_column<ColumnMap>(
1016
12
            dst->is_nullable() ? static_cast<ColumnNullable&>(*dst).get_nested_column() : *dst);
1017
12
    auto offsets_ptr = column_map->get_offsets_column().assume_mutable();
1018
12
    auto& offsets = static_cast<ColumnArray::ColumnOffsets&>(*offsets_ptr);
1019
12
    size_t base = offsets.get_data().empty() ? 0 : offsets.get_data().back();
1020
1021
    // 1. bulk read null-map if nullable
1022
12
    std::vector<uint8_t> null_mask; // 0: not null, 1: null
1023
12
    if (_map_reader->is_nullable()) {
1024
        // For nullable map columns, the destination column must also be nullable.
1025
0
        if (UNLIKELY(!dst->is_nullable())) {
1026
0
            return Status::InternalError(
1027
0
                    "unexpected non-nullable destination column for nullable map reader");
1028
0
        }
1029
0
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1030
0
        size_t null_before = null_map_ptr->size();
1031
0
        RETURN_IF_ERROR(_null_iterator->read_by_rowids(rowids, count, null_map_ptr));
1032
        // extract a light-weight view to decide element reads
1033
0
        auto& null_map_col = assert_cast<ColumnUInt8&>(*null_map_ptr);
1034
0
        null_mask.reserve(count);
1035
0
        for (size_t i = 0; i < count; ++i) {
1036
0
            null_mask.push_back(null_map_col.get_element(null_before + i));
1037
0
        }
1038
12
    } else if (dst->is_nullable()) {
1039
        // in not-null to null linked-schemachange mode,
1040
        // actually we do not change dat data include meta in footer,
1041
        // so may dst from changed meta which is nullable but old data is not nullable,
1042
        // if so, we should set null_map to all null by default
1043
0
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1044
0
        auto& null_map = assert_cast<ColumnUInt8&>(*null_map_ptr);
1045
0
        null_map.insert_many_vals(0, count);
1046
0
    }
1047
1048
    // 2. bulk read start ordinals for requested rows
1049
12
    MutableColumnPtr starts_col = ColumnOffset64::create();
1050
12
    starts_col->reserve(count);
1051
12
    RETURN_IF_ERROR(_offsets_iterator->read_by_rowids(rowids, count, starts_col));
1052
1053
    // 3. bulk read next-start ordinals for rowid+1 (within bounds)
1054
12
    std::vector<rowid_t> next_rowids(count);
1055
3.44k
    for (size_t i = 0; i < count; ++i) {
1056
3.43k
        uint64_t nr = rowids[i] + 1;
1057
3.43k
        next_rowids[i] = nr < _map_reader->num_rows() ? static_cast<rowid_t>(nr)
1058
3.43k
                                                      : static_cast<rowid_t>(0); // placeholder
1059
3.43k
    }
1060
12
    MutableColumnPtr next_starts_col = ColumnOffset64::create();
1061
12
    next_starts_col->reserve(count);
1062
    // read for all; we'll fix out-of-bound cases below
1063
12
    RETURN_IF_ERROR(_offsets_iterator->read_by_rowids(next_rowids.data(), count, next_starts_col));
1064
1065
    // 4. fix next_start for rows whose next_rowid is out-of-bound (rowid == num_rows-1)
1066
3.44k
    for (size_t i = 0; i < count; ++i) {
1067
3.43k
        if (rowids[i] + 1 >= _map_reader->num_rows()) {
1068
            // seek to the last row and consume one to move decoder to end-of-page,
1069
            // then peek page-tail sentinel next_array_item_ordinal as next_start
1070
2
            RETURN_IF_ERROR(_offsets_iterator->seek_to_ordinal(rowids[i]));
1071
2
            size_t one = 1;
1072
2
            bool has_null_unused = false;
1073
2
            MutableColumnPtr tmp = ColumnOffset64::create();
1074
2
            RETURN_IF_ERROR(_offsets_iterator->next_batch(&one, tmp, &has_null_unused));
1075
2
            ordinal_t ns = 0;
1076
2
            RETURN_IF_ERROR(_offsets_iterator->_peek_one_offset(&ns));
1077
            // overwrite with sentinel
1078
2
            assert_cast<ColumnOffset64&, TypeCheckOnRelease::DISABLE>(*next_starts_col)
1079
2
                    .get_data()[i] = ns;
1080
2
        }
1081
3.43k
    }
1082
1083
    // 5. compute sizes and append offsets prefix-sum
1084
12
    auto& starts_data = assert_cast<ColumnOffset64&>(*starts_col).get_data();
1085
12
    auto& next_starts_data = assert_cast<ColumnOffset64&>(*next_starts_col).get_data();
1086
12
    std::vector<size_t> sizes(count, 0);
1087
12
    size_t acc = base;
1088
12
    const auto original_size = offsets.get_data().back();
1089
12
    offsets.get_data().reserve(offsets.get_data().size() + count);
1090
3.44k
    for (size_t i = 0; i < count; ++i) {
1091
3.43k
        size_t sz = static_cast<size_t>(next_starts_data[i] - starts_data[i]);
1092
3.43k
        if (_map_reader->is_nullable() && !null_mask.empty() && null_mask[i]) {
1093
0
            sz = 0; // null rows do not consume elements
1094
0
        }
1095
3.43k
        sizes[i] = sz;
1096
3.43k
        acc += sz;
1097
3.43k
        offsets.get_data().push_back(acc);
1098
3.43k
    }
1099
1100
    // 6. read key/value elements for non-empty sizes
1101
12
    auto keys_ptr = column_map->get_keys().assume_mutable();
1102
12
    auto vals_ptr = column_map->get_values().assume_mutable();
1103
1104
12
    size_t this_run = sizes[0];
1105
12
    auto start_idx = starts_data[0];
1106
12
    auto last_idx = starts_data[0] + this_run;
1107
3.43k
    for (size_t i = 1; i < count; ++i) {
1108
3.41k
        size_t sz = sizes[i];
1109
3.41k
        if (sz == 0) {
1110
3.10k
            continue;
1111
3.10k
        }
1112
317
        auto start = static_cast<ordinal_t>(starts_data[i]);
1113
317
        if (start != last_idx) {
1114
310
            size_t n = this_run;
1115
310
            bool dummy_has_null = false;
1116
1117
310
            if (this_run != 0) {
1118
309
                if (_key_iterator->reading_flag() != ReadingFlag::SKIP_READING) {
1119
309
                    RETURN_IF_ERROR(_key_iterator->seek_to_ordinal(start_idx));
1120
309
                    RETURN_IF_ERROR(_key_iterator->next_batch(&n, keys_ptr, &dummy_has_null));
1121
309
                    DCHECK(n == this_run);
1122
309
                }
1123
1124
309
                if (_val_iterator->reading_flag() != ReadingFlag::SKIP_READING) {
1125
309
                    n = this_run;
1126
309
                    RETURN_IF_ERROR(_val_iterator->seek_to_ordinal(start_idx));
1127
309
                    RETURN_IF_ERROR(_val_iterator->next_batch(&n, vals_ptr, &dummy_has_null));
1128
309
                    DCHECK(n == this_run);
1129
309
                }
1130
309
            }
1131
310
            start_idx = start;
1132
310
            this_run = sz;
1133
310
            last_idx = start + sz;
1134
310
            continue;
1135
310
        }
1136
1137
7
        this_run += sz;
1138
7
        last_idx += sz;
1139
7
    }
1140
1141
12
    size_t n = this_run;
1142
12
    const size_t total_count = offsets.get_data().back() - original_size;
1143
12
    bool dummy_has_null = false;
1144
12
    if (_key_iterator->reading_flag() != ReadingFlag::SKIP_READING) {
1145
12
        if (this_run != 0) {
1146
5
            RETURN_IF_ERROR(_key_iterator->seek_to_ordinal(start_idx));
1147
5
            RETURN_IF_ERROR(_key_iterator->next_batch(&n, keys_ptr, &dummy_has_null));
1148
5
            DCHECK(n == this_run);
1149
5
        }
1150
12
    } else {
1151
0
        keys_ptr->insert_many_defaults(total_count);
1152
0
    }
1153
1154
12
    if (_val_iterator->reading_flag() != ReadingFlag::SKIP_READING) {
1155
12
        if (this_run != 0) {
1156
5
            n = this_run;
1157
5
            RETURN_IF_ERROR(_val_iterator->seek_to_ordinal(start_idx));
1158
5
            RETURN_IF_ERROR(_val_iterator->next_batch(&n, vals_ptr, &dummy_has_null));
1159
5
            DCHECK(n == this_run);
1160
5
        }
1161
12
    } else {
1162
0
        vals_ptr->insert_many_defaults(total_count);
1163
0
    }
1164
1165
12
    return Status::OK();
1166
12
}
1167
1168
0
void MapFileColumnIterator::set_need_to_read() {
1169
0
    set_reading_flag(ReadingFlag::NEED_TO_READ);
1170
0
    _key_iterator->set_need_to_read();
1171
0
    _val_iterator->set_need_to_read();
1172
0
}
1173
1174
0
void MapFileColumnIterator::remove_pruned_sub_iterators() {
1175
0
    _key_iterator->remove_pruned_sub_iterators();
1176
0
    _val_iterator->remove_pruned_sub_iterators();
1177
0
}
1178
1179
Status MapFileColumnIterator::set_access_paths(const TColumnAccessPaths& all_access_paths,
1180
1
                                               const TColumnAccessPaths& predicate_access_paths) {
1181
1
    if (all_access_paths.empty()) {
1182
0
        return Status::OK();
1183
0
    }
1184
1185
1
    if (!predicate_access_paths.empty()) {
1186
0
        set_reading_flag(ReadingFlag::READING_FOR_PREDICATE);
1187
0
        DLOG(INFO) << "Map column iterator set sub-column " << _column_name
1188
0
                   << " to READING_FOR_PREDICATE";
1189
0
    }
1190
1191
1
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
1192
1
    auto sub_predicate_access_paths = DORIS_TRY(_get_sub_access_paths(predicate_access_paths));
1193
1194
1
    if (sub_all_access_paths.empty()) {
1195
0
        return Status::OK();
1196
0
    }
1197
1198
1
    TColumnAccessPaths key_all_access_paths;
1199
1
    TColumnAccessPaths val_all_access_paths;
1200
1
    TColumnAccessPaths key_predicate_access_paths;
1201
1
    TColumnAccessPaths val_predicate_access_paths;
1202
1203
1
    for (auto paths : sub_all_access_paths) {
1204
1
        if (paths.data_access_path.path[0] == "*") {
1205
0
            paths.data_access_path.path[0] = _key_iterator->column_name();
1206
0
            key_all_access_paths.emplace_back(paths);
1207
0
            paths.data_access_path.path[0] = _val_iterator->column_name();
1208
0
            val_all_access_paths.emplace_back(paths);
1209
1
        } else if (paths.data_access_path.path[0] == "KEYS") {
1210
1
            paths.data_access_path.path[0] = _key_iterator->column_name();
1211
1
            key_all_access_paths.emplace_back(paths);
1212
1
        } else if (paths.data_access_path.path[0] == "VALUES") {
1213
0
            paths.data_access_path.path[0] = _val_iterator->column_name();
1214
0
            val_all_access_paths.emplace_back(paths);
1215
0
        }
1216
1
    }
1217
1
    const auto need_read_keys = !key_all_access_paths.empty();
1218
1
    const auto need_read_values = !val_all_access_paths.empty();
1219
1220
1
    for (auto paths : sub_predicate_access_paths) {
1221
0
        if (paths.data_access_path.path[0] == "*") {
1222
0
            paths.data_access_path.path[0] = _key_iterator->column_name();
1223
0
            key_predicate_access_paths.emplace_back(paths);
1224
0
            paths.data_access_path.path[0] = _val_iterator->column_name();
1225
0
            val_predicate_access_paths.emplace_back(paths);
1226
0
        } else if (paths.data_access_path.path[0] == "KEYS") {
1227
0
            paths.data_access_path.path[0] = _key_iterator->column_name();
1228
0
            key_predicate_access_paths.emplace_back(paths);
1229
0
        } else if (paths.data_access_path.path[0] == "VALUES") {
1230
0
            paths.data_access_path.path[0] = _val_iterator->column_name();
1231
0
            val_predicate_access_paths.emplace_back(paths);
1232
0
        }
1233
0
    }
1234
1235
1
    if (need_read_keys) {
1236
1
        _key_iterator->set_reading_flag(ReadingFlag::NEED_TO_READ);
1237
1
        RETURN_IF_ERROR(
1238
1
                _key_iterator->set_access_paths(key_all_access_paths, key_predicate_access_paths));
1239
1
    } else {
1240
0
        _key_iterator->set_reading_flag(ReadingFlag::SKIP_READING);
1241
0
        DLOG(INFO) << "Map column iterator set key column to SKIP_READING";
1242
0
    }
1243
1244
1
    if (need_read_values) {
1245
0
        _val_iterator->set_reading_flag(ReadingFlag::NEED_TO_READ);
1246
0
        RETURN_IF_ERROR(
1247
0
                _val_iterator->set_access_paths(val_all_access_paths, val_predicate_access_paths));
1248
1
    } else {
1249
1
        _val_iterator->set_reading_flag(ReadingFlag::SKIP_READING);
1250
1
        DLOG(INFO) << "Map column iterator set value column to SKIP_READING";
1251
1
    }
1252
1
    return Status::OK();
1253
1
}
1254
1255
////////////////////////////////////////////////////////////////////////////////
1256
1257
StructFileColumnIterator::StructFileColumnIterator(
1258
        std::shared_ptr<ColumnReader> reader, ColumnIteratorUPtr null_iterator,
1259
        std::vector<ColumnIteratorUPtr>&& sub_column_iterators)
1260
4
        : _struct_reader(reader), _sub_column_iterators(std::move(sub_column_iterators)) {
1261
4
    if (_struct_reader->is_nullable()) {
1262
0
        _null_iterator = std::move(null_iterator);
1263
0
    }
1264
4
}
1265
1266
0
Status StructFileColumnIterator::init(const ColumnIteratorOptions& opts) {
1267
0
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1268
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1269
0
        return Status::OK();
1270
0
    }
1271
1272
0
    for (auto& column_iterator : _sub_column_iterators) {
1273
0
        RETURN_IF_ERROR(column_iterator->init(opts));
1274
0
    }
1275
0
    if (_struct_reader->is_nullable()) {
1276
0
        RETURN_IF_ERROR(_null_iterator->init(opts));
1277
0
    }
1278
0
    return Status::OK();
1279
0
}
1280
1281
0
Status StructFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
1282
0
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1283
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1284
0
        dst->insert_many_defaults(*n);
1285
0
        return Status::OK();
1286
0
    }
1287
1288
0
    auto& column_struct = assert_cast<ColumnStruct&, TypeCheckOnRelease::DISABLE>(
1289
0
            dst->is_nullable() ? static_cast<ColumnNullable&>(*dst).get_nested_column() : *dst);
1290
0
    for (size_t i = 0; i < column_struct.tuple_size(); i++) {
1291
0
        size_t num_read = *n;
1292
0
        auto sub_column_ptr = column_struct.get_column(i).assume_mutable();
1293
0
        bool column_has_null = false;
1294
0
        RETURN_IF_ERROR(
1295
0
                _sub_column_iterators[i]->next_batch(&num_read, sub_column_ptr, &column_has_null));
1296
0
        DCHECK(num_read == *n);
1297
0
        column_struct.get_column_ptr(i) = std::move(sub_column_ptr);
1298
0
    }
1299
1300
0
    if (dst->is_nullable()) {
1301
0
        size_t num_read = *n;
1302
0
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1303
        // in not-null to null linked-schemachange mode,
1304
        // actually we do not change dat data include meta in footer,
1305
        // so may dst from changed meta which is nullable but old data is not nullable,
1306
        // if so, we should set null_map to all null by default
1307
0
        if (_null_iterator) {
1308
0
            bool null_signs_has_null = false;
1309
0
            RETURN_IF_ERROR(
1310
0
                    _null_iterator->next_batch(&num_read, null_map_ptr, &null_signs_has_null));
1311
0
        } else {
1312
0
            auto& null_map = assert_cast<ColumnUInt8&, TypeCheckOnRelease::DISABLE>(*null_map_ptr);
1313
0
            null_map.insert_many_vals(0, num_read);
1314
0
        }
1315
0
        DCHECK(num_read == *n);
1316
0
    }
1317
1318
0
    return Status::OK();
1319
0
}
1320
1321
0
Status StructFileColumnIterator::seek_to_ordinal(ordinal_t ord) {
1322
0
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1323
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1324
0
        return Status::OK();
1325
0
    }
1326
1327
0
    for (auto& column_iterator : _sub_column_iterators) {
1328
0
        RETURN_IF_ERROR(column_iterator->seek_to_ordinal(ord));
1329
0
    }
1330
0
    if (_struct_reader->is_nullable()) {
1331
0
        RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
1332
0
    }
1333
0
    return Status::OK();
1334
0
}
1335
1336
0
Status StructFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
1337
0
    for (auto& column_iterator : _sub_column_iterators) {
1338
0
        RETURN_IF_ERROR(column_iterator->init_prefetcher(params));
1339
0
    }
1340
0
    if (_struct_reader->is_nullable()) {
1341
0
        RETURN_IF_ERROR(_null_iterator->init_prefetcher(params));
1342
0
    }
1343
0
    return Status::OK();
1344
0
}
1345
1346
void StructFileColumnIterator::collect_prefetchers(
1347
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
1348
0
        PrefetcherInitMethod init_method) {
1349
0
    for (auto& column_iterator : _sub_column_iterators) {
1350
0
        column_iterator->collect_prefetchers(prefetchers, init_method);
1351
0
    }
1352
0
    if (_struct_reader->is_nullable()) {
1353
0
        _null_iterator->collect_prefetchers(prefetchers, init_method);
1354
0
    }
1355
0
}
1356
1357
Status StructFileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
1358
0
                                                MutableColumnPtr& dst) {
1359
0
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1360
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1361
0
        dst->insert_many_defaults(count);
1362
0
        return Status::OK();
1363
0
    }
1364
1365
0
    if (count == 0) {
1366
0
        return Status::OK();
1367
0
    }
1368
1369
0
    size_t this_run = 1;
1370
0
    auto start_idx = rowids[0];
1371
0
    auto last_idx = rowids[0];
1372
0
    for (size_t i = 1; i < count; ++i) {
1373
0
        if (last_idx == rowids[i] - 1) {
1374
0
            last_idx = rowids[i];
1375
0
            this_run++;
1376
0
            continue;
1377
0
        }
1378
0
        RETURN_IF_ERROR(seek_to_ordinal(start_idx));
1379
0
        size_t num_read = this_run;
1380
0
        RETURN_IF_ERROR(next_batch(&num_read, dst, nullptr));
1381
0
        DCHECK_EQ(num_read, this_run);
1382
1383
0
        start_idx = rowids[i];
1384
0
        last_idx = rowids[i];
1385
0
        this_run = 1;
1386
0
    }
1387
1388
0
    RETURN_IF_ERROR(seek_to_ordinal(start_idx));
1389
0
    size_t num_read = this_run;
1390
0
    RETURN_IF_ERROR(next_batch(&num_read, dst, nullptr));
1391
0
    DCHECK_EQ(num_read, this_run);
1392
0
    return Status::OK();
1393
0
}
1394
1395
1
void StructFileColumnIterator::set_need_to_read() {
1396
1
    set_reading_flag(ReadingFlag::NEED_TO_READ);
1397
2
    for (auto& sub_iterator : _sub_column_iterators) {
1398
2
        sub_iterator->set_need_to_read();
1399
2
    }
1400
1
}
1401
1402
0
void StructFileColumnIterator::remove_pruned_sub_iterators() {
1403
0
    for (auto it = _sub_column_iterators.begin(); it != _sub_column_iterators.end();) {
1404
0
        auto& sub_iterator = *it;
1405
0
        if (sub_iterator->reading_flag() == ReadingFlag::SKIP_READING) {
1406
0
            DLOG(INFO) << "Struct column iterator remove pruned sub-column "
1407
0
                       << sub_iterator->column_name();
1408
0
            it = _sub_column_iterators.erase(it);
1409
0
        } else {
1410
0
            sub_iterator->remove_pruned_sub_iterators();
1411
0
            ++it;
1412
0
        }
1413
0
    }
1414
0
}
1415
1416
Status StructFileColumnIterator::set_access_paths(
1417
        const TColumnAccessPaths& all_access_paths,
1418
6
        const TColumnAccessPaths& predicate_access_paths) {
1419
6
    if (all_access_paths.empty()) {
1420
1
        return Status::OK();
1421
1
    }
1422
1423
5
    if (!predicate_access_paths.empty()) {
1424
4
        set_reading_flag(ReadingFlag::READING_FOR_PREDICATE);
1425
4
        DLOG(INFO) << "Struct column iterator set sub-column " << _column_name
1426
4
                   << " to READING_FOR_PREDICATE";
1427
4
    }
1428
5
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
1429
3
    auto sub_predicate_access_paths = DORIS_TRY(_get_sub_access_paths(predicate_access_paths));
1430
1431
3
    const auto no_sub_column_to_skip = sub_all_access_paths.empty();
1432
3
    const auto no_predicate_sub_column = sub_predicate_access_paths.empty();
1433
1434
6
    for (auto& sub_iterator : _sub_column_iterators) {
1435
6
        const auto name = sub_iterator->column_name();
1436
6
        bool need_to_read = no_sub_column_to_skip;
1437
6
        TColumnAccessPaths sub_all_access_paths_of_this;
1438
6
        if (!need_to_read) {
1439
4
            for (const auto& paths : sub_all_access_paths) {
1440
4
                if (paths.data_access_path.path[0] == name) {
1441
2
                    sub_all_access_paths_of_this.emplace_back(paths);
1442
2
                }
1443
4
            }
1444
4
            need_to_read = !sub_all_access_paths_of_this.empty();
1445
4
        }
1446
1447
6
        if (!need_to_read) {
1448
2
            set_reading_flag(ReadingFlag::SKIP_READING);
1449
2
            sub_iterator->set_reading_flag(ReadingFlag::SKIP_READING);
1450
2
            DLOG(INFO) << "Struct column iterator set sub-column " << name << " to SKIP_READING";
1451
2
            continue;
1452
2
        }
1453
4
        set_reading_flag(ReadingFlag::NEED_TO_READ);
1454
4
        sub_iterator->set_reading_flag(ReadingFlag::NEED_TO_READ);
1455
1456
4
        TColumnAccessPaths sub_predicate_access_paths_of_this;
1457
1458
4
        if (!no_predicate_sub_column) {
1459
3
            for (const auto& paths : sub_predicate_access_paths) {
1460
3
                if (StringCaseEqual()(paths.data_access_path.path[0], name)) {
1461
2
                    sub_predicate_access_paths_of_this.emplace_back(paths);
1462
2
                }
1463
3
            }
1464
3
        }
1465
1466
4
        RETURN_IF_ERROR(sub_iterator->set_access_paths(sub_all_access_paths_of_this,
1467
4
                                                       sub_predicate_access_paths_of_this));
1468
4
    }
1469
3
    return Status::OK();
1470
3
}
1471
1472
////////////////////////////////////////////////////////////////////////////////
1473
336
Status OffsetFileColumnIterator::init(const ColumnIteratorOptions& opts) {
1474
336
    RETURN_IF_ERROR(_offset_iterator->init(opts));
1475
    // allocate peek tmp column once
1476
336
    _peek_tmp_col = ColumnOffset64::create();
1477
336
    return Status::OK();
1478
336
}
1479
1480
361
Status OffsetFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
1481
361
    RETURN_IF_ERROR(_offset_iterator->next_batch(n, dst, has_null));
1482
361
    return Status::OK();
1483
361
}
1484
1485
725
Status OffsetFileColumnIterator::_peek_one_offset(ordinal_t* offset) {
1486
725
    if (_offset_iterator->get_current_page()->has_remaining()) {
1487
386
        PageDecoder* offset_page_decoder = _offset_iterator->get_current_page()->data_decoder.get();
1488
386
        size_t n = 1;
1489
386
        _peek_tmp_col->clear();
1490
386
        RETURN_IF_ERROR(offset_page_decoder->peek_next_batch(&n, _peek_tmp_col)); // not null
1491
386
        DCHECK(_peek_tmp_col->size() == 1);
1492
386
        *offset =
1493
386
                assert_cast<const ColumnOffset64*, TypeCheckOnRelease::DISABLE>(_peek_tmp_col.get())
1494
386
                        ->get_element(0);
1495
386
    } else {
1496
339
        *offset = _offset_iterator->get_current_page()->next_array_item_ordinal;
1497
339
    }
1498
725
    return Status::OK();
1499
725
}
1500
1501
0
Status OffsetFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
1502
0
    return _offset_iterator->init_prefetcher(params);
1503
0
}
1504
1505
void OffsetFileColumnIterator::collect_prefetchers(
1506
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
1507
0
        PrefetcherInitMethod init_method) {
1508
0
    _offset_iterator->collect_prefetchers(prefetchers, init_method);
1509
0
}
1510
1511
/**
1512
 *  first_storage_offset read from page should smaller than next_storage_offset which here call _peek_one_offset from page,
1513
    and first_column_offset is keep in memory data which is different dimension with (first_storage_offset and next_storage_offset)
1514
     eg. step1. read page: first_storage_offset = 16382
1515
         step2. read page below with _peek_one_offset(&last_offset): last_offset = 16387
1516
         step3. first_offset = 126 which is calculate in column offsets
1517
         for loop column offsets element in size
1518
            we can calculate from first_storage_offset to next_storage_offset one by one to fill with offsets_data in memory column offsets
1519
 * @param start
1520
 * @param column_offsets
1521
 * @return
1522
 */
1523
Status OffsetFileColumnIterator::_calculate_offsets(ssize_t start,
1524
360
                                                    ColumnArray::ColumnOffsets& column_offsets) {
1525
360
    ordinal_t next_storage_offset = 0;
1526
360
    RETURN_IF_ERROR(_peek_one_offset(&next_storage_offset));
1527
1528
    // calculate real offsets
1529
360
    auto& offsets_data = column_offsets.get_data();
1530
360
    ordinal_t first_column_offset = offsets_data[start - 1]; // -1 is valid
1531
360
    ordinal_t first_storage_offset = offsets_data[start];
1532
360
    DCHECK(next_storage_offset >= first_storage_offset);
1533
144k
    for (ssize_t i = start; i < offsets_data.size() - 1; ++i) {
1534
144k
        offsets_data[i] = first_column_offset + (offsets_data[i + 1] - first_storage_offset);
1535
144k
    }
1536
    // last offset
1537
360
    offsets_data[offsets_data.size() - 1] =
1538
360
            first_column_offset + (next_storage_offset - first_storage_offset);
1539
360
    return Status::OK();
1540
360
}
1541
1542
////////////////////////////////////////////////////////////////////////////////
1543
ArrayFileColumnIterator::ArrayFileColumnIterator(std::shared_ptr<ColumnReader> reader,
1544
                                                 OffsetFileColumnIteratorUPtr offset_reader,
1545
                                                 ColumnIteratorUPtr item_iterator,
1546
                                                 ColumnIteratorUPtr null_iterator)
1547
59
        : _array_reader(reader),
1548
59
          _offset_iterator(std::move(offset_reader)),
1549
59
          _item_iterator(std::move(item_iterator)) {
1550
59
    if (_array_reader->is_nullable()) {
1551
56
        _null_iterator = std::move(null_iterator);
1552
56
    }
1553
59
}
1554
1555
58
Status ArrayFileColumnIterator::init(const ColumnIteratorOptions& opts) {
1556
58
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1557
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip readking.";
1558
0
        return Status::OK();
1559
0
    }
1560
1561
58
    RETURN_IF_ERROR(_offset_iterator->init(opts));
1562
58
    RETURN_IF_ERROR(_item_iterator->init(opts));
1563
58
    if (_array_reader->is_nullable()) {
1564
56
        RETURN_IF_ERROR(_null_iterator->init(opts));
1565
56
    }
1566
58
    return Status::OK();
1567
58
}
1568
1569
68
Status ArrayFileColumnIterator::_seek_by_offsets(ordinal_t ord) {
1570
    // using offsets info
1571
68
    ordinal_t offset = 0;
1572
68
    RETURN_IF_ERROR(_offset_iterator->_peek_one_offset(&offset));
1573
68
    RETURN_IF_ERROR(_item_iterator->seek_to_ordinal(offset));
1574
68
    return Status::OK();
1575
68
}
1576
1577
68
Status ArrayFileColumnIterator::seek_to_ordinal(ordinal_t ord) {
1578
68
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1579
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip reading.";
1580
0
        return Status::OK();
1581
0
    }
1582
1583
68
    RETURN_IF_ERROR(_offset_iterator->seek_to_ordinal(ord));
1584
68
    if (_array_reader->is_nullable()) {
1585
66
        RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
1586
66
    }
1587
68
    return _seek_by_offsets(ord);
1588
68
}
1589
1590
66
Status ArrayFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
1591
66
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1592
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip reading.";
1593
0
        dst->insert_many_defaults(*n);
1594
0
        return Status::OK();
1595
0
    }
1596
1597
66
    const auto* column_array = check_and_get_column<ColumnArray>(
1598
66
            dst->is_nullable() ? static_cast<ColumnNullable&>(*dst).get_nested_column() : *dst);
1599
1600
66
    bool offsets_has_null = false;
1601
66
    auto column_offsets_ptr = column_array->get_offsets_column().assume_mutable();
1602
66
    ssize_t start = column_offsets_ptr->size();
1603
66
    RETURN_IF_ERROR(_offset_iterator->next_batch(n, column_offsets_ptr, &offsets_has_null));
1604
66
    if (*n == 0) {
1605
0
        return Status::OK();
1606
0
    }
1607
66
    auto& column_offsets = static_cast<ColumnArray::ColumnOffsets&>(*column_offsets_ptr);
1608
66
    RETURN_IF_ERROR(_offset_iterator->_calculate_offsets(start, column_offsets));
1609
66
    size_t num_items =
1610
66
            column_offsets.get_data().back() - column_offsets.get_data()[start - 1]; // -1 is valid
1611
66
    auto column_items_ptr = column_array->get_data().assume_mutable();
1612
66
    if (num_items > 0) {
1613
46
        size_t num_read = num_items;
1614
46
        bool items_has_null = false;
1615
46
        RETURN_IF_ERROR(_item_iterator->next_batch(&num_read, column_items_ptr, &items_has_null));
1616
46
        DCHECK(num_read == num_items);
1617
46
    }
1618
1619
66
    if (dst->is_nullable()) {
1620
64
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1621
64
        size_t num_read = *n;
1622
        // in not-null to null linked-schemachange mode,
1623
        // actually we do not change dat data include meta in footer,
1624
        // so may dst from changed meta which is nullable but old data is not nullable,
1625
        // if so, we should set null_map to all null by default
1626
64
        if (_null_iterator) {
1627
64
            bool null_signs_has_null = false;
1628
64
            RETURN_IF_ERROR(
1629
64
                    _null_iterator->next_batch(&num_read, null_map_ptr, &null_signs_has_null));
1630
64
        } else {
1631
0
            auto& null_map = assert_cast<ColumnUInt8&, TypeCheckOnRelease::DISABLE>(*null_map_ptr);
1632
0
            null_map.insert_many_vals(0, num_read);
1633
0
        }
1634
64
        DCHECK(num_read == *n);
1635
64
    }
1636
1637
66
    return Status::OK();
1638
66
}
1639
1640
0
Status ArrayFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
1641
0
    RETURN_IF_ERROR(_offset_iterator->init_prefetcher(params));
1642
0
    RETURN_IF_ERROR(_item_iterator->init_prefetcher(params));
1643
0
    if (_array_reader->is_nullable()) {
1644
0
        RETURN_IF_ERROR(_null_iterator->init_prefetcher(params));
1645
0
    }
1646
0
    return Status::OK();
1647
0
}
1648
1649
void ArrayFileColumnIterator::collect_prefetchers(
1650
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
1651
0
        PrefetcherInitMethod init_method) {
1652
0
    _offset_iterator->collect_prefetchers(prefetchers, init_method);
1653
    // the actual data pages to read of item column depends on the read result of offset column,
1654
    // so we can't init prefetch blocks according to rowids, just prefetch all data blocks here.
1655
0
    _item_iterator->collect_prefetchers(prefetchers, PrefetcherInitMethod::ALL_DATA_BLOCKS);
1656
0
    if (_array_reader->is_nullable()) {
1657
0
        _null_iterator->collect_prefetchers(prefetchers, init_method);
1658
0
    }
1659
0
}
1660
1661
Status ArrayFileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
1662
0
                                               MutableColumnPtr& dst) {
1663
0
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1664
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip reading.";
1665
0
        dst->insert_many_defaults(count);
1666
0
        return Status::OK();
1667
0
    }
1668
1669
0
    for (size_t i = 0; i < count; ++i) {
1670
        // TODO(cambyzju): now read array one by one, need optimize later
1671
0
        RETURN_IF_ERROR(seek_to_ordinal(rowids[i]));
1672
0
        size_t num_read = 1;
1673
0
        RETURN_IF_ERROR(next_batch(&num_read, dst, nullptr));
1674
0
        DCHECK(num_read == 1);
1675
0
    }
1676
0
    return Status::OK();
1677
0
}
1678
1679
0
void ArrayFileColumnIterator::set_need_to_read() {
1680
0
    set_reading_flag(ReadingFlag::NEED_TO_READ);
1681
0
    _item_iterator->set_need_to_read();
1682
0
}
1683
1684
0
void ArrayFileColumnIterator::remove_pruned_sub_iterators() {
1685
0
    _item_iterator->remove_pruned_sub_iterators();
1686
0
}
1687
1688
Status ArrayFileColumnIterator::set_access_paths(const TColumnAccessPaths& all_access_paths,
1689
1
                                                 const TColumnAccessPaths& predicate_access_paths) {
1690
1
    if (all_access_paths.empty()) {
1691
0
        return Status::OK();
1692
0
    }
1693
1694
1
    if (!predicate_access_paths.empty()) {
1695
0
        set_reading_flag(ReadingFlag::READING_FOR_PREDICATE);
1696
0
        DLOG(INFO) << "Array column iterator set sub-column " << _column_name
1697
0
                   << " to READING_FOR_PREDICATE";
1698
0
    }
1699
1700
1
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
1701
1
    auto sub_predicate_access_paths = DORIS_TRY(_get_sub_access_paths(predicate_access_paths));
1702
1703
1
    const auto no_sub_column_to_skip = sub_all_access_paths.empty();
1704
1
    const auto no_predicate_sub_column = sub_predicate_access_paths.empty();
1705
1706
1
    if (!no_sub_column_to_skip) {
1707
1
        for (auto& path : sub_all_access_paths) {
1708
1
            if (path.data_access_path.path[0] == "*") {
1709
1
                path.data_access_path.path[0] = _item_iterator->column_name();
1710
1
            }
1711
1
        }
1712
1
    }
1713
1714
1
    if (!no_predicate_sub_column) {
1715
0
        for (auto& path : sub_predicate_access_paths) {
1716
0
            if (path.data_access_path.path[0] == "*") {
1717
0
                path.data_access_path.path[0] = _item_iterator->column_name();
1718
0
            }
1719
0
        }
1720
0
    }
1721
1722
1
    if (!no_sub_column_to_skip || !no_predicate_sub_column) {
1723
1
        _item_iterator->set_reading_flag(ReadingFlag::NEED_TO_READ);
1724
1
        RETURN_IF_ERROR(
1725
1
                _item_iterator->set_access_paths(sub_all_access_paths, sub_predicate_access_paths));
1726
1
    }
1727
1
    return Status::OK();
1728
1
}
1729
1730
////////////////////////////////////////////////////////////////////////////////
1731
1732
188k
FileColumnIterator::FileColumnIterator(std::shared_ptr<ColumnReader> reader) : _reader(reader) {}
1733
1734
185k
Status FileColumnIterator::init(const ColumnIteratorOptions& opts) {
1735
185k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1736
0
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
1737
0
        return Status::OK();
1738
0
    }
1739
1740
185k
    _opts = opts;
1741
186k
    if (!_opts.use_page_cache) {
1742
186k
        _reader->disable_index_meta_cache();
1743
186k
    }
1744
185k
    RETURN_IF_ERROR(get_block_compression_codec(_reader->get_compression(), &_compress_codec));
1745
185k
    if (config::enable_low_cardinality_optimize &&
1746
186k
        opts.io_ctx.reader_type == ReaderType::READER_QUERY &&
1747
185k
        _reader->encoding_info()->encoding() == DICT_ENCODING) {
1748
105k
        auto dict_encoding_type = _reader->get_dict_encoding_type();
1749
        // Only if the column is a predicate column, then we need check the all dict encoding flag
1750
        // because we could rewrite the predciate to accelarate query speed. But if it is not a
1751
        // predicate column, then it is useless. And it has a bad impact on cold read(first time read)
1752
        // because it will load the column's ordinal index and zonemap index and maybe other indices.
1753
        // it has bad impact on primary key query. For example, select * from table where pk = 1, and
1754
        // the table has 2000 columns.
1755
105k
        if (dict_encoding_type == ColumnReader::UNKNOWN_DICT_ENCODING && opts.is_predicate_column) {
1756
202
            RETURN_IF_ERROR(seek_to_ordinal(_reader->num_rows() - 1));
1757
202
            _is_all_dict_encoding = _page.is_dict_encoding;
1758
202
            _reader->set_dict_encoding_type(_is_all_dict_encoding
1759
202
                                                    ? ColumnReader::ALL_DICT_ENCODING
1760
202
                                                    : ColumnReader::PARTIAL_DICT_ENCODING);
1761
105k
        } else {
1762
105k
            _is_all_dict_encoding = dict_encoding_type == ColumnReader::ALL_DICT_ENCODING;
1763
105k
        }
1764
105k
    }
1765
185k
    return Status::OK();
1766
185k
}
1767
1768
188k
FileColumnIterator::~FileColumnIterator() = default;
1769
1770
0
void FileColumnIterator::_trigger_prefetch_if_eligible(ordinal_t ord) {
1771
0
    std::vector<BlockRange> ranges;
1772
0
    if (_prefetcher->need_prefetch(cast_set<uint32_t>(ord), &ranges)) {
1773
0
        for (const auto& range : ranges) {
1774
0
            _cached_remote_file_reader->prefetch_range(range.offset, range.size, &_opts.io_ctx);
1775
0
        }
1776
0
    }
1777
0
}
1778
1779
45.7k
Status FileColumnIterator::seek_to_ordinal(ordinal_t ord) {
1780
45.7k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1781
0
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
1782
0
        return Status::OK();
1783
0
    }
1784
1785
45.7k
    LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
1786
0
            "[verbose] FileColumnIterator::seek_to_ordinal seek to ordinal {}, enable_prefetch={}",
1787
0
            ord, _enable_prefetch);
1788
45.7k
    if (_enable_prefetch) {
1789
0
        _trigger_prefetch_if_eligible(ord);
1790
0
    }
1791
1792
    // if current page contains this row, we don't need to seek
1793
45.7k
    if (!_page || !_page.contains(ord) || !_page_iter.valid()) {
1794
24.1k
        RETURN_IF_ERROR(_reader->seek_at_or_before(ord, &_page_iter, _opts));
1795
24.1k
        RETURN_IF_ERROR(_read_data_page(_page_iter));
1796
24.1k
    }
1797
45.7k
    RETURN_IF_ERROR(_seek_to_pos_in_page(&_page, ord - _page.first_ordinal));
1798
45.7k
    _current_ordinal = ord;
1799
45.7k
    return Status::OK();
1800
45.7k
}
1801
1802
0
Status FileColumnIterator::seek_to_page_start() {
1803
0
    return seek_to_ordinal(_page.first_ordinal);
1804
0
}
1805
1806
47.4k
Status FileColumnIterator::_seek_to_pos_in_page(ParsedPage* page, ordinal_t offset_in_page) const {
1807
47.4k
    if (page->offset_in_page == offset_in_page) {
1808
        // fast path, do nothing
1809
40.7k
        return Status::OK();
1810
40.7k
    }
1811
1812
6.69k
    ordinal_t pos_in_data = offset_in_page;
1813
6.69k
    if (_page.has_null) {
1814
435
        ordinal_t offset_in_data = 0;
1815
435
        ordinal_t skips = offset_in_page;
1816
1817
435
        if (offset_in_page > page->offset_in_page) {
1818
            // forward, reuse null bitmap
1819
312
            skips = offset_in_page - page->offset_in_page;
1820
312
            offset_in_data = page->data_decoder->current_index();
1821
312
        } else {
1822
            // rewind null bitmap, and
1823
123
            page->null_decoder = RleDecoder<bool>((const uint8_t*)page->null_bitmap.data,
1824
123
                                                  cast_set<int>(page->null_bitmap.size), 1);
1825
123
        }
1826
1827
435
        auto skip_nulls = page->null_decoder.Skip(skips);
1828
435
        pos_in_data = offset_in_data + skips - skip_nulls;
1829
435
    }
1830
1831
6.69k
    RETURN_IF_ERROR(page->data_decoder->seek_to_position_in_page(pos_in_data));
1832
6.69k
    page->offset_in_page = offset_in_page;
1833
6.69k
    return Status::OK();
1834
6.69k
}
1835
1836
1.61k
Status FileColumnIterator::next_batch_of_zone_map(size_t* n, MutableColumnPtr& dst) {
1837
1.61k
    return _reader->next_batch_of_zone_map(n, dst);
1838
1.61k
}
1839
1840
35.2k
Status FileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
1841
35.2k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1842
0
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
1843
0
        dst->insert_many_defaults(*n);
1844
0
        return Status::OK();
1845
0
    }
1846
1847
35.2k
    size_t curr_size = dst->byte_size();
1848
35.2k
    dst->reserve(*n);
1849
35.2k
    size_t remaining = *n;
1850
35.2k
    *has_null = false;
1851
72.2k
    while (remaining > 0) {
1852
36.9k
        if (!_page.has_remaining()) {
1853
1.76k
            bool eos = false;
1854
1.76k
            RETURN_IF_ERROR(_load_next_page(&eos));
1855
1.76k
            if (eos) {
1856
0
                break;
1857
0
            }
1858
1.76k
        }
1859
1860
        // number of rows to be read from this page
1861
36.9k
        size_t nrows_in_page = std::min(remaining, _page.remaining());
1862
36.9k
        size_t nrows_to_read = nrows_in_page;
1863
36.9k
        if (_page.has_null) {
1864
27.2k
            while (nrows_to_read > 0) {
1865
25.7k
                bool is_null = false;
1866
25.7k
                size_t this_run = _page.null_decoder.GetNextRun(&is_null, nrows_to_read);
1867
                // we use num_rows only for CHECK
1868
25.7k
                size_t num_rows = this_run;
1869
25.7k
                if (!is_null) {
1870
13.1k
                    RETURN_IF_ERROR(_page.data_decoder->next_batch(&num_rows, dst));
1871
13.1k
                    DCHECK_EQ(this_run, num_rows);
1872
13.1k
                } else {
1873
12.6k
                    *has_null = true;
1874
12.6k
                    auto* null_col = check_and_get_column<ColumnNullable>(dst.get());
1875
12.6k
                    if (null_col != nullptr) {
1876
12.6k
                        null_col->insert_many_defaults(this_run);
1877
18.4E
                    } else {
1878
18.4E
                        return Status::InternalError("unexpected column type in column reader");
1879
18.4E
                    }
1880
12.6k
                }
1881
1882
25.7k
                nrows_to_read -= this_run;
1883
25.7k
                _page.offset_in_page += this_run;
1884
25.7k
                _current_ordinal += this_run;
1885
25.7k
            }
1886
35.4k
        } else {
1887
35.4k
            RETURN_IF_ERROR(_page.data_decoder->next_batch(&nrows_to_read, dst));
1888
35.4k
            DCHECK_EQ(nrows_to_read, nrows_in_page);
1889
1890
35.4k
            _page.offset_in_page += nrows_to_read;
1891
35.4k
            _current_ordinal += nrows_to_read;
1892
35.4k
        }
1893
36.9k
        remaining -= nrows_in_page;
1894
36.9k
    }
1895
35.2k
    *n -= remaining;
1896
35.2k
    _opts.stats->bytes_read += (dst->byte_size() - curr_size) + BitmapSize(*n);
1897
1898
#ifdef BE_TEST
1899
    _reader->check_data_by_zone_map_for_test(dst);
1900
#endif
1901
35.2k
    return Status::OK();
1902
35.2k
}
1903
1904
Status FileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
1905
9.76k
                                          MutableColumnPtr& dst) {
1906
9.76k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1907
0
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
1908
0
        dst->insert_many_defaults(count);
1909
0
        return Status::OK();
1910
0
    }
1911
1912
9.76k
    size_t remaining = count;
1913
9.76k
    size_t total_read_count = 0;
1914
9.76k
    size_t nrows_to_read = 0;
1915
20.0k
    while (remaining > 0) {
1916
10.2k
        RETURN_IF_ERROR(seek_to_ordinal(rowids[total_read_count]));
1917
1918
        // number of rows to be read from this page
1919
10.2k
        nrows_to_read = std::min(remaining, _page.remaining());
1920
1921
10.2k
        if (_page.has_null) {
1922
731
            size_t already_read = 0;
1923
10.6k
            while ((nrows_to_read - already_read) > 0) {
1924
9.93k
                bool is_null = false;
1925
9.93k
                size_t this_run = std::min(nrows_to_read - already_read, _page.remaining());
1926
9.93k
                if (UNLIKELY(this_run == 0)) {
1927
0
                    break;
1928
0
                }
1929
9.93k
                this_run = _page.null_decoder.GetNextRun(&is_null, this_run);
1930
9.93k
                size_t offset = total_read_count + already_read;
1931
9.93k
                size_t this_read_count = 0;
1932
9.93k
                rowid_t current_ordinal_in_page =
1933
9.93k
                        cast_set<uint32_t>(_page.offset_in_page + _page.first_ordinal);
1934
122k
                for (size_t i = 0; i < this_run; ++i) {
1935
114k
                    if (rowids[offset + i] - current_ordinal_in_page >= this_run) {
1936
1.53k
                        break;
1937
1.53k
                    }
1938
112k
                    this_read_count++;
1939
112k
                }
1940
1941
9.93k
                auto origin_index = _page.data_decoder->current_index();
1942
9.93k
                if (this_read_count > 0) {
1943
8.80k
                    if (is_null) {
1944
4.14k
                        auto* null_col = check_and_get_column<ColumnNullable>(dst.get());
1945
4.14k
                        if (UNLIKELY(null_col == nullptr)) {
1946
0
                            return Status::InternalError("unexpected column type in column reader");
1947
0
                        }
1948
1949
4.14k
                        null_col->insert_many_defaults(this_read_count);
1950
4.66k
                    } else {
1951
4.66k
                        size_t read_count = this_read_count;
1952
1953
                        // ordinal in nullable columns' data buffer maybe be not continuously(the data doesn't contain null value),
1954
                        // so we need use `page_start_off_in_decoder` to calculate the actual offset in `data_decoder`
1955
4.66k
                        size_t page_start_off_in_decoder =
1956
4.66k
                                _page.first_ordinal + _page.offset_in_page - origin_index;
1957
4.66k
                        RETURN_IF_ERROR(_page.data_decoder->read_by_rowids(
1958
4.66k
                                &rowids[offset], page_start_off_in_decoder, &read_count, dst));
1959
4.66k
                        DCHECK_EQ(read_count, this_read_count);
1960
4.66k
                    }
1961
8.80k
                }
1962
1963
9.93k
                if (!is_null) {
1964
4.78k
                    RETURN_IF_ERROR(
1965
4.78k
                            _page.data_decoder->seek_to_position_in_page(origin_index + this_run));
1966
4.78k
                }
1967
1968
9.93k
                already_read += this_read_count;
1969
9.93k
                _page.offset_in_page += this_run;
1970
9.93k
                DCHECK(_page.offset_in_page <= _page.num_rows);
1971
9.93k
            }
1972
1973
731
            nrows_to_read = already_read;
1974
731
            total_read_count += nrows_to_read;
1975
731
            remaining -= nrows_to_read;
1976
9.55k
        } else {
1977
9.55k
            RETURN_IF_ERROR(_page.data_decoder->read_by_rowids(
1978
9.55k
                    &rowids[total_read_count], _page.first_ordinal, &nrows_to_read, dst));
1979
9.55k
            total_read_count += nrows_to_read;
1980
9.55k
            remaining -= nrows_to_read;
1981
9.55k
        }
1982
10.2k
    }
1983
9.76k
    return Status::OK();
1984
9.76k
}
1985
1986
1.76k
Status FileColumnIterator::_load_next_page(bool* eos) {
1987
1.76k
    _page_iter.next();
1988
1.76k
    if (!_page_iter.valid()) {
1989
0
        *eos = true;
1990
0
        return Status::OK();
1991
0
    }
1992
1993
1.76k
    RETURN_IF_ERROR(_read_data_page(_page_iter));
1994
1.76k
    RETURN_IF_ERROR(_seek_to_pos_in_page(&_page, 0));
1995
1.76k
    *eos = false;
1996
1.76k
    return Status::OK();
1997
1.76k
}
1998
1999
25.9k
Status FileColumnIterator::_read_data_page(const OrdinalPageIndexIterator& iter) {
2000
25.9k
    PageHandle handle;
2001
25.9k
    Slice page_body;
2002
25.9k
    PageFooterPB footer;
2003
25.9k
    _opts.type = DATA_PAGE;
2004
25.9k
    RETURN_IF_ERROR(
2005
25.9k
            _reader->read_page(_opts, iter.page(), &handle, &page_body, &footer, _compress_codec));
2006
    // parse data page
2007
25.9k
    auto st = ParsedPage::create(std::move(handle), page_body, footer.data_page_footer(),
2008
25.9k
                                 _reader->encoding_info(), iter.page(), iter.page_index(), &_page);
2009
25.9k
    if (!st.ok()) {
2010
0
        LOG(WARNING) << "failed to create ParsedPage, file=" << _opts.file_reader->path().native()
2011
0
                     << ", page_offset=" << iter.page().offset << ", page_size=" << iter.page().size
2012
0
                     << ", page_index=" << iter.page_index() << ", error=" << st;
2013
0
        return st;
2014
0
    }
2015
2016
    // dictionary page is read when the first data page that uses it is read,
2017
    // this is to optimize the memory usage: when there is no query on one column, we could
2018
    // release the memory of dictionary page.
2019
    // note that concurrent iterators for the same column won't repeatedly read dictionary page
2020
    // because of page cache.
2021
25.9k
    if (_reader->encoding_info()->encoding() == DICT_ENCODING) {
2022
9.90k
        auto dict_page_decoder = reinterpret_cast<BinaryDictPageDecoder*>(_page.data_decoder.get());
2023
9.90k
        if (dict_page_decoder->is_dict_encoding()) {
2024
8.28k
            if (_dict_decoder == nullptr) {
2025
8.28k
                RETURN_IF_ERROR(_read_dict_data());
2026
8.28k
                CHECK_NOTNULL(_dict_decoder);
2027
8.28k
            }
2028
2029
8.27k
            dict_page_decoder->set_dict_decoder(cast_set<uint32_t>(_dict_decoder->count()),
2030
8.27k
                                                _dict_word_info.get());
2031
8.27k
        }
2032
9.90k
    }
2033
25.9k
    return Status::OK();
2034
25.9k
}
2035
2036
8.27k
Status FileColumnIterator::_read_dict_data() {
2037
8.27k
    CHECK_EQ(_reader->encoding_info()->encoding(), DICT_ENCODING);
2038
    // read dictionary page
2039
8.27k
    Slice dict_data;
2040
8.27k
    PageFooterPB dict_footer;
2041
8.27k
    _opts.type = INDEX_PAGE;
2042
2043
8.27k
    RETURN_IF_ERROR(_reader->read_page(_opts, _reader->get_dict_page_pointer(), &_dict_page_handle,
2044
8.27k
                                       &dict_data, &dict_footer, _compress_codec, true));
2045
8.27k
    const EncodingInfo* encoding_info;
2046
8.27k
    RETURN_IF_ERROR(EncodingInfo::get(FieldType::OLAP_FIELD_TYPE_VARCHAR,
2047
8.27k
                                      dict_footer.dict_page_footer().encoding(), {},
2048
8.27k
                                      &encoding_info));
2049
8.27k
    RETURN_IF_ERROR(encoding_info->create_page_decoder(dict_data, {}, _dict_decoder));
2050
8.27k
    RETURN_IF_ERROR(_dict_decoder->init());
2051
2052
8.27k
    _dict_word_info.reset(new StringRef[_dict_decoder->count()]);
2053
8.27k
    RETURN_IF_ERROR(_dict_decoder->get_dict_word_info(_dict_word_info.get()));
2054
8.27k
    return Status::OK();
2055
8.27k
}
2056
2057
Status FileColumnIterator::get_row_ranges_by_zone_map(
2058
        const AndBlockColumnPredicate* col_predicates,
2059
        const std::vector<std::shared_ptr<const ColumnPredicate>>* delete_predicates,
2060
550
        RowRanges* row_ranges) {
2061
552
    if (_reader->has_zone_map()) {
2062
552
        RETURN_IF_ERROR(_reader->get_row_ranges_by_zone_map(col_predicates, delete_predicates,
2063
552
                                                            row_ranges, _opts));
2064
552
    }
2065
550
    return Status::OK();
2066
550
}
2067
2068
Status FileColumnIterator::get_row_ranges_by_bloom_filter(
2069
552
        const AndBlockColumnPredicate* col_predicates, RowRanges* row_ranges) {
2070
552
    if ((col_predicates->can_do_bloom_filter(false) && _reader->has_bloom_filter_index(false)) ||
2071
552
        (col_predicates->can_do_bloom_filter(true) && _reader->has_bloom_filter_index(true))) {
2072
0
        RETURN_IF_ERROR(_reader->get_row_ranges_by_bloom_filter(col_predicates, row_ranges, _opts));
2073
0
    }
2074
552
    return Status::OK();
2075
552
}
2076
2077
Status FileColumnIterator::get_row_ranges_by_dict(const AndBlockColumnPredicate* col_predicates,
2078
568
                                                  RowRanges* row_ranges) {
2079
568
    if (!_is_all_dict_encoding) {
2080
368
        return Status::OK();
2081
368
    }
2082
2083
200
    if (!_dict_decoder) {
2084
0
        RETURN_IF_ERROR(_read_dict_data());
2085
0
        CHECK_NOTNULL(_dict_decoder);
2086
0
    }
2087
2088
200
    if (!col_predicates->evaluate_and(_dict_word_info.get(), _dict_decoder->count())) {
2089
16
        row_ranges->clear();
2090
16
    }
2091
200
    return Status::OK();
2092
200
}
2093
2094
0
Status FileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
2095
0
    if (_cached_remote_file_reader =
2096
0
                std::dynamic_pointer_cast<io::CachedRemoteFileReader>(_reader->_file_reader);
2097
0
        !_cached_remote_file_reader) {
2098
0
        return Status::OK();
2099
0
    }
2100
0
    _enable_prefetch = true;
2101
0
    _prefetcher = std::make_unique<SegmentPrefetcher>(params.config);
2102
0
    RETURN_IF_ERROR(_prefetcher->init(_reader, params.read_options));
2103
0
    return Status::OK();
2104
0
}
2105
2106
void FileColumnIterator::collect_prefetchers(
2107
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
2108
0
        PrefetcherInitMethod init_method) {
2109
0
    if (_prefetcher) {
2110
0
        prefetchers[init_method].emplace_back(_prefetcher.get());
2111
0
    }
2112
0
}
2113
2114
3
Status DefaultValueColumnIterator::init(const ColumnIteratorOptions& opts) {
2115
3
    _opts = opts;
2116
    // be consistent with segment v1
2117
    // if _has_default_value, we should create default column iterator for this column, and
2118
    // "NULL" is a special default value which means the default value is null.
2119
3
    if (_has_default_value) {
2120
1
        if (_default_value == "NULL") {
2121
1
            _default_value_field = Field::create_field<TYPE_NULL>(Null {});
2122
1
        } else {
2123
0
            if (_type_info->type() == FieldType::OLAP_FIELD_TYPE_ARRAY) {
2124
0
                if (_default_value != "[]") {
2125
0
                    return Status::NotSupported("Array default {} is unsupported", _default_value);
2126
0
                } else {
2127
0
                    _default_value_field = Field::create_field<TYPE_ARRAY>(Array {});
2128
0
                    return Status::OK();
2129
0
                }
2130
0
            } else if (_type_info->type() == FieldType::OLAP_FIELD_TYPE_STRUCT) {
2131
0
                return Status::NotSupported("STRUCT default type is unsupported");
2132
0
            } else if (_type_info->type() == FieldType::OLAP_FIELD_TYPE_MAP) {
2133
0
                return Status::NotSupported("MAP default type is unsupported");
2134
0
            }
2135
0
            const auto t = _type_info->type();
2136
0
            const auto serde = DataTypeFactory::instance()
2137
0
                                       .create_data_type(t, _precision, _scale, _len)
2138
0
                                       ->get_serde();
2139
0
            DataTypeSerDe::FormatOptions opt;
2140
0
            RETURN_IF_ERROR(serde->from_olap_string(_default_value, _default_value_field, opt));
2141
0
        }
2142
2
    } else if (_is_nullable) {
2143
2
        _default_value_field = Field::create_field<TYPE_NULL>(Null {});
2144
2
    } else {
2145
0
        return Status::InternalError(
2146
0
                "invalid default value column for no default value and not nullable");
2147
0
    }
2148
3
    return Status::OK();
2149
3
}
2150
2151
0
Status DefaultValueColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
2152
0
    *has_null = _default_value_field.is_null();
2153
0
    _insert_many_default(dst, *n);
2154
0
    return Status::OK();
2155
0
}
2156
2157
Status DefaultValueColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
2158
0
                                                  MutableColumnPtr& dst) {
2159
0
    _insert_many_default(dst, count);
2160
0
    return Status::OK();
2161
0
}
2162
2163
0
void DefaultValueColumnIterator::_insert_many_default(MutableColumnPtr& dst, size_t n) {
2164
0
    if (_default_value_field.is_null()) {
2165
0
        dst->insert_many_defaults(n);
2166
0
    } else {
2167
0
        dst = dst->convert_to_predicate_column_if_dictionary();
2168
0
        dst->insert_duplicate_fields(_default_value_field, n);
2169
0
    }
2170
0
}
2171
2172
10
Status RowIdColumnIteratorV2::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
2173
10
    auto* string_column = assert_cast<ColumnString*, TypeCheckOnRelease::DISABLE>(dst.get());
2174
2175
20
    for (uint32_t i = 0; i < *n; ++i) {
2176
10
        uint32_t row_id = _current_rowid + i;
2177
10
        GlobalRowLoacationV2 location(_version, _backend_id, _file_id, row_id);
2178
10
        string_column->insert_data(reinterpret_cast<const char*>(&location),
2179
10
                                   sizeof(GlobalRowLoacationV2));
2180
10
    }
2181
10
    _current_rowid += *n;
2182
10
    return Status::OK();
2183
10
}
2184
2185
Status RowIdColumnIteratorV2::read_by_rowids(const rowid_t* rowids, const size_t count,
2186
5
                                             MutableColumnPtr& dst) {
2187
5
    auto* string_column = assert_cast<ColumnString*>(dst.get());
2188
2189
19
    for (size_t i = 0; i < count; ++i) {
2190
14
        uint32_t row_id = rowids[i];
2191
14
        GlobalRowLoacationV2 location(_version, _backend_id, _file_id, row_id);
2192
14
        string_column->insert_data(reinterpret_cast<const char*>(&location),
2193
14
                                   sizeof(GlobalRowLoacationV2));
2194
14
    }
2195
5
    return Status::OK();
2196
5
}
2197
#include "common/compile_check_end.h"
2198
2199
} // namespace doris::segment_v2