Coverage Report

Created: 2026-05-26 02:45

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/defer_op.h"
81
#include "util/rle_encoding.h" // for RleDecoder
82
#include "util/slice.h"
83
84
namespace doris::segment_v2 {
85
#include "storage/segment/column_reader.h"
86
87
891
inline bool read_as_string(PrimitiveType type) {
88
891
    return type == PrimitiveType::TYPE_STRING || type == PrimitiveType::INVALID_TYPE ||
89
891
           type == PrimitiveType::TYPE_BITMAP || type == PrimitiveType::TYPE_FIXED_LENGTH_OBJECT;
90
891
}
91
92
Status ColumnReader::create_array(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
93
                                  const io::FileReaderSPtr& file_reader,
94
66.1k
                                  std::shared_ptr<ColumnReader>* reader) {
95
66.1k
    DCHECK(meta.children_columns_size() == 2 || meta.children_columns_size() == 3);
96
97
66.1k
    std::shared_ptr<ColumnReader> item_reader;
98
66.1k
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(0),
99
66.1k
                                         meta.children_columns(0).num_rows(), file_reader,
100
66.1k
                                         &item_reader));
101
102
66.1k
    std::shared_ptr<ColumnReader> offset_reader;
103
66.1k
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(1),
104
66.1k
                                         meta.children_columns(1).num_rows(), file_reader,
105
66.1k
                                         &offset_reader));
106
107
66.1k
    std::shared_ptr<ColumnReader> null_reader;
108
66.1k
    if (meta.is_nullable()) {
109
47.3k
        RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(2),
110
47.3k
                                             meta.children_columns(2).num_rows(), file_reader,
111
47.3k
                                             &null_reader));
112
47.3k
    }
113
114
    // The num rows of the array reader equals to the num rows of the length reader.
115
66.1k
    uint64_t array_num_rows = meta.children_columns(1).num_rows();
116
66.1k
    std::shared_ptr<ColumnReader> array_reader(
117
66.1k
            new ColumnReader(opts, meta, array_num_rows, file_reader));
118
    //  array reader do not need to init
119
66.1k
    array_reader->_sub_readers.resize(meta.children_columns_size());
120
66.1k
    array_reader->_sub_readers[0] = std::move(item_reader);
121
66.1k
    array_reader->_sub_readers[1] = std::move(offset_reader);
122
66.1k
    if (meta.is_nullable()) {
123
47.2k
        array_reader->_sub_readers[2] = std::move(null_reader);
124
47.2k
    }
125
66.1k
    array_reader->_meta_type = FieldType::OLAP_FIELD_TYPE_ARRAY;
126
66.1k
    *reader = std::move(array_reader);
127
66.1k
    return Status::OK();
128
66.1k
}
129
130
Status ColumnReader::create_map(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
131
                                const io::FileReaderSPtr& file_reader,
132
68.0k
                                std::shared_ptr<ColumnReader>* reader) {
133
    // map reader now has 3 sub readers for key, value, offsets(scalar), null(scala)
134
68.0k
    DCHECK(meta.children_columns_size() == 3 || meta.children_columns_size() == 4);
135
68.0k
    std::shared_ptr<ColumnReader> key_reader;
136
68.0k
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(0),
137
68.0k
                                         meta.children_columns(0).num_rows(), file_reader,
138
68.0k
                                         &key_reader));
139
68.0k
    std::shared_ptr<ColumnReader> val_reader;
140
68.0k
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(1),
141
68.0k
                                         meta.children_columns(1).num_rows(), file_reader,
142
68.0k
                                         &val_reader));
143
68.0k
    std::shared_ptr<ColumnReader> offset_reader;
144
68.0k
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(2),
145
68.0k
                                         meta.children_columns(2).num_rows(), file_reader,
146
68.0k
                                         &offset_reader));
147
68.0k
    std::shared_ptr<ColumnReader> null_reader;
148
68.0k
    if (meta.is_nullable()) {
149
15.4k
        RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(3),
150
15.4k
                                             meta.children_columns(3).num_rows(), file_reader,
151
15.4k
                                             &null_reader));
152
15.4k
    }
153
154
    // The num rows of the map reader equals to the num rows of the length reader.
155
68.0k
    uint64_t map_num_rows = meta.children_columns(2).num_rows();
156
68.0k
    std::shared_ptr<ColumnReader> map_reader(
157
68.0k
            new ColumnReader(opts, meta, map_num_rows, file_reader));
158
68.0k
    map_reader->_sub_readers.resize(meta.children_columns_size());
159
160
68.0k
    map_reader->_sub_readers[0] = std::move(key_reader);
161
68.0k
    map_reader->_sub_readers[1] = std::move(val_reader);
162
68.0k
    map_reader->_sub_readers[2] = std::move(offset_reader);
163
68.0k
    if (meta.is_nullable()) {
164
15.4k
        map_reader->_sub_readers[3] = std::move(null_reader);
165
15.4k
    }
166
68.0k
    map_reader->_meta_type = FieldType::OLAP_FIELD_TYPE_MAP;
167
68.0k
    *reader = std::move(map_reader);
168
68.0k
    return Status::OK();
169
68.0k
}
170
171
Status ColumnReader::create_struct(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
172
                                   uint64_t num_rows, const io::FileReaderSPtr& file_reader,
173
7.75k
                                   std::shared_ptr<ColumnReader>* reader) {
174
    // not support empty struct
175
7.75k
    DCHECK(meta.children_columns_size() >= 1);
176
    // create struct column reader
177
7.75k
    std::shared_ptr<ColumnReader> struct_reader(
178
7.75k
            new ColumnReader(opts, meta, num_rows, file_reader));
179
7.75k
    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
40.9k
    for (int i = 0; i < meta.children_columns_size(); i++) {
182
33.2k
        std::shared_ptr<ColumnReader> sub_reader;
183
33.2k
        RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(i),
184
33.2k
                                             meta.children_columns(i).num_rows(), file_reader,
185
33.2k
                                             &sub_reader));
186
33.2k
        struct_reader->_sub_readers.push_back(std::move(sub_reader));
187
33.2k
    }
188
7.75k
    struct_reader->_meta_type = FieldType::OLAP_FIELD_TYPE_STRUCT;
189
7.75k
    *reader = std::move(struct_reader);
190
7.75k
    return Status::OK();
191
7.75k
}
192
193
Status ColumnReader::create_agg_state(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
194
                                      uint64_t num_rows, const io::FileReaderSPtr& file_reader,
195
895
                                      std::shared_ptr<ColumnReader>* reader) {
196
895
    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
895
    auto data_type = DataTypeFactory::instance().create_data_type(meta);
205
895
    const auto* agg_state_type = assert_cast<const DataTypeAggState*>(data_type.get());
206
895
    agg_state_type->check_function_compatibility(opts.be_exec_version);
207
895
    auto type = agg_state_type->get_serialized_type()->get_primitive_type();
208
209
895
    if (read_as_string(type)) {
210
831
        std::shared_ptr<ColumnReader> reader_local(
211
831
                new ColumnReader(opts, meta, num_rows, file_reader));
212
831
        RETURN_IF_ERROR(reader_local->init(&meta));
213
831
        *reader = std::move(reader_local);
214
831
        return Status::OK();
215
831
    } else if (type == PrimitiveType::TYPE_MAP) {
216
47
        return create_map(opts, meta, file_reader, reader);
217
47
    } else if (type == PrimitiveType::TYPE_ARRAY) {
218
13
        return create_array(opts, meta, file_reader, reader);
219
13
    } else if (type == PrimitiveType::TYPE_STRUCT) {
220
0
        return create_struct(opts, meta, num_rows, file_reader, reader);
221
0
    }
222
223
4
    return Status::InternalError("Not supported type: {}, serialized type: {}",
224
4
                                 agg_state_type->get_name(), int(type));
225
895
}
226
227
98.6k
bool ColumnReader::is_compaction_reader_type(ReaderType type) {
228
98.6k
    return type == ReaderType::READER_BASE_COMPACTION ||
229
98.6k
           type == ReaderType::READER_CUMULATIVE_COMPACTION ||
230
98.6k
           type == ReaderType::READER_COLD_DATA_COMPACTION ||
231
98.6k
           type == ReaderType::READER_SEGMENT_COMPACTION ||
232
98.6k
           type == ReaderType::READER_FULL_COMPACTION;
233
98.6k
}
234
235
Status ColumnReader::create(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
236
                            uint64_t num_rows, const io::FileReaderSPtr& file_reader,
237
21.3M
                            std::shared_ptr<ColumnReader>* reader) {
238
21.3M
    if (is_scalar_type((FieldType)meta.type())) {
239
21.1M
        std::shared_ptr<ColumnReader> reader_local(
240
21.1M
                new ColumnReader(opts, meta, num_rows, file_reader));
241
21.1M
        RETURN_IF_ERROR(reader_local->init(&meta));
242
21.1M
        *reader = std::move(reader_local);
243
21.1M
        return Status::OK();
244
21.1M
    } else {
245
160k
        auto type = (FieldType)meta.type();
246
160k
        switch (type) {
247
896
        case FieldType::OLAP_FIELD_TYPE_AGG_STATE: {
248
896
            return create_agg_state(opts, meta, num_rows, file_reader, reader);
249
0
        }
250
7.75k
        case FieldType::OLAP_FIELD_TYPE_STRUCT: {
251
7.75k
            return create_struct(opts, meta, num_rows, file_reader, reader);
252
0
        }
253
66.2k
        case FieldType::OLAP_FIELD_TYPE_ARRAY: {
254
66.2k
            return create_array(opts, meta, file_reader, reader);
255
0
        }
256
68.0k
        case FieldType::OLAP_FIELD_TYPE_MAP: {
257
68.0k
            return create_map(opts, meta, file_reader, reader);
258
0
        }
259
18.7k
        case FieldType::OLAP_FIELD_TYPE_VARIANT: {
260
            // Read variant only root data using a single ColumnReader
261
18.7k
            std::shared_ptr<ColumnReader> reader_local(
262
18.7k
                    new ColumnReader(opts, meta, num_rows, file_reader));
263
18.7k
            RETURN_IF_ERROR(reader_local->init(&meta));
264
18.7k
            *reader = std::move(reader_local);
265
18.7k
            return Status::OK();
266
18.7k
        }
267
0
        default:
268
0
            return Status::NotSupported("unsupported type for ColumnReader: {}",
269
0
                                        std::to_string(int(type)));
270
160k
        }
271
160k
    }
272
21.3M
}
273
274
18.7k
ColumnReader::ColumnReader() = default;
275
276
ColumnReader::ColumnReader(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
277
                           uint64_t num_rows, io::FileReaderSPtr file_reader)
278
21.3M
        : _use_index_page_cache(!config::disable_storage_page_cache),
279
21.3M
          _opts(opts),
280
21.3M
          _num_rows(num_rows),
281
21.3M
          _file_reader(std::move(file_reader)),
282
21.3M
          _dict_encoding_type(UNKNOWN_DICT_ENCODING) {
283
21.3M
    _meta_length = meta.length();
284
21.3M
    _meta_type = (FieldType)meta.type();
285
21.3M
    if (_meta_type == FieldType::OLAP_FIELD_TYPE_ARRAY) {
286
66.1k
        _meta_children_column_type = (FieldType)meta.children_columns(0).type();
287
66.1k
    }
288
21.3M
    _data_type = DataTypeFactory::instance().create_data_type(meta);
289
21.3M
    _meta_is_nullable = meta.is_nullable();
290
21.3M
    _meta_dict_page = meta.dict_page();
291
21.3M
    _meta_compression = meta.compression();
292
21.3M
}
293
294
21.4M
ColumnReader::~ColumnReader() = default;
295
296
21.2M
int64_t ColumnReader::get_metadata_size() const {
297
21.2M
    return sizeof(ColumnReader) + (_segment_zone_map ? _segment_zone_map->ByteSizeLong() : 0);
298
21.2M
}
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;
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
21.1M
Status ColumnReader::init(const ColumnMetaPB* meta) {
350
21.1M
    _type = (FieldType)meta->type();
351
352
21.1M
    if (meta->has_be_exec_version()) {
353
20.8M
        _be_exec_version = meta->be_exec_version();
354
20.8M
    }
355
356
21.2M
    if (_type == FieldType::OLAP_FIELD_TYPE_NONE || _type == FieldType::OLAP_FIELD_TYPE_UNKNOWN) {
357
0
        return Status::NotSupported("unsupported typeinfo, type={}", meta->type());
358
0
    }
359
21.1M
    RETURN_IF_ERROR(EncodingInfo::get(_type, meta->encoding(), {}, &_encoding_info));
360
361
62.9M
    for (int i = 0; i < meta->indexes_size(); i++) {
362
41.7M
        const auto& index_meta = meta->indexes(i);
363
41.7M
        switch (index_meta.type()) {
364
0
        case BITMAP_INDEX:
365
0
            break;
366
21.1M
        case ORDINAL_INDEX:
367
21.1M
            _ordinal_index.reset(
368
21.1M
                    new OrdinalIndexReader(_file_reader, _num_rows, index_meta.ordinal_index()));
369
21.1M
            break;
370
20.6M
        case ZONE_MAP_INDEX:
371
20.6M
            _segment_zone_map =
372
20.6M
                    std::make_unique<ZoneMapPB>(index_meta.zone_map_index().segment_zone_map());
373
20.6M
            _zone_map_index.reset(new ZoneMapIndexReader(
374
20.6M
                    _file_reader, index_meta.zone_map_index().page_zone_maps()));
375
20.6M
            break;
376
4.93k
        case BLOOM_FILTER_INDEX:
377
4.93k
            _bloom_filter_index.reset(
378
4.93k
                    new BloomFilterIndexReader(_file_reader, index_meta.bloom_filter_index()));
379
4.93k
            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
41.7M
        }
386
41.7M
    }
387
21.1M
    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
21.1M
    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
21.1M
    return Status::OK();
397
21.1M
}
398
399
Status ColumnReader::new_index_iterator(const std::shared_ptr<IndexFileReader>& index_file_reader,
400
                                        const TabletIndex* index_meta, const std::string& rowset_id,
401
                                        uint32_t segment_id, size_t rows_of_segment,
402
74.4k
                                        std::unique_ptr<IndexIterator>* iterator) {
403
74.4k
    RETURN_IF_ERROR(
404
74.4k
            _load_index(index_file_reader, index_meta, rowset_id, segment_id, rows_of_segment));
405
74.4k
    {
406
74.4k
        std::shared_lock<std::shared_mutex> rlock(_load_index_lock);
407
74.4k
        auto iter = _index_readers.find(index_meta->index_id());
408
74.6k
        if (iter != _index_readers.end()) {
409
74.6k
            if (iter->second != nullptr) {
410
74.6k
                RETURN_IF_ERROR(iter->second->new_iterator(iterator));
411
74.6k
            }
412
74.6k
        }
413
74.4k
    }
414
74.4k
    return Status::OK();
415
74.4k
}
416
417
Status ColumnReader::read_page(const ColumnIteratorOptions& iter_opts, const PagePointer& pp,
418
                               PageHandle* handle, Slice* page_body, PageFooterPB* footer,
419
1.97M
                               BlockCompressionCodec* codec, bool is_dict_page) const {
420
1.97M
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().column_reader_read_page);
421
1.97M
    iter_opts.sanity_check();
422
1.97M
    PageReadOptions opts(iter_opts.io_ctx);
423
1.97M
    opts.verify_checksum = _opts.verify_checksum;
424
1.97M
    opts.use_page_cache = iter_opts.use_page_cache;
425
1.97M
    opts.kept_in_memory = _opts.kept_in_memory;
426
1.97M
    opts.type = iter_opts.type;
427
1.97M
    opts.file_reader = iter_opts.file_reader;
428
1.97M
    opts.page_pointer = pp;
429
1.97M
    opts.codec = codec;
430
1.97M
    opts.stats = iter_opts.stats;
431
1.97M
    opts.encoding_info = _encoding_info;
432
1.97M
    opts.is_dict_page = is_dict_page;
433
434
1.97M
    return PageIO::read_and_decompress_page(opts, handle, page_body, footer);
435
1.97M
}
436
437
Status ColumnReader::get_row_ranges_by_zone_map(
438
        const AndBlockColumnPredicate* col_predicates,
439
        const std::vector<std::shared_ptr<const ColumnPredicate>>* delete_predicates,
440
107k
        RowRanges* row_ranges, const ColumnIteratorOptions& iter_opts) {
441
107k
    std::vector<uint32_t> page_indexes;
442
107k
    RETURN_IF_ERROR(
443
107k
            _get_filtered_pages(col_predicates, delete_predicates, &page_indexes, iter_opts));
444
107k
    RETURN_IF_ERROR(_calculate_row_ranges(page_indexes, row_ranges, iter_opts));
445
107k
    return Status::OK();
446
107k
}
447
448
10.8k
Status ColumnReader::next_batch_of_zone_map(size_t* n, MutableColumnPtr& dst) const {
449
10.8k
    if (_segment_zone_map == nullptr) {
450
0
        return Status::InternalError("segment zonemap not exist");
451
0
    }
452
    // TODO: this work to get min/max value seems should only do once
453
10.8k
    ZoneMap zone_map;
454
10.8k
    RETURN_IF_ERROR(ZoneMap::from_proto(*_segment_zone_map, _data_type, zone_map));
455
456
10.8k
    dst->reserve(*n);
457
10.8k
    if (!zone_map.has_not_null) {
458
701
        assert_cast<ColumnNullable&>(*dst).insert_many_defaults(*n);
459
701
        return Status::OK();
460
701
    }
461
10.1k
    dst->insert(zone_map.max_value);
462
20.2k
    for (int i = 1; i < *n; ++i) {
463
10.1k
        dst->insert(zone_map.min_value);
464
10.1k
    }
465
10.1k
    return Status::OK();
466
10.8k
}
467
468
Status ColumnReader::match_condition(const AndBlockColumnPredicate* col_predicates,
469
1.82M
                                     bool* matched) const {
470
1.82M
    *matched = true;
471
1.82M
    if (_zone_map_index == nullptr) {
472
0
        return Status::OK();
473
0
    }
474
1.82M
    ZoneMap zone_map;
475
1.82M
    RETURN_IF_ERROR(ZoneMap::from_proto(*_segment_zone_map, _data_type, zone_map));
476
477
1.82M
    *matched = _zone_map_match_condition(zone_map, col_predicates);
478
1.82M
    return Status::OK();
479
1.82M
}
480
481
Status ColumnReader::prune_predicates_by_zone_map(
482
        std::vector<std::shared_ptr<ColumnPredicate>>& predicates, const int column_id,
483
8.61M
        bool* pruned) const {
484
8.61M
    *pruned = false;
485
8.61M
    if (_zone_map_index == nullptr) {
486
1.33k
        return Status::OK();
487
1.33k
    }
488
489
8.61M
    ZoneMap zone_map;
490
8.61M
    RETURN_IF_ERROR(ZoneMap::from_proto(*_segment_zone_map, _data_type, zone_map));
491
8.61M
    if (zone_map.pass_all) {
492
0
        return Status::OK();
493
0
    }
494
495
17.3M
    for (auto it = predicates.begin(); it != predicates.end();) {
496
8.78M
        auto predicate = *it;
497
8.78M
        if (predicate->column_id() == column_id && predicate->is_always_true(zone_map)) {
498
10.1k
            *pruned = true;
499
10.1k
            it = predicates.erase(it);
500
8.77M
        } else {
501
8.77M
            ++it;
502
8.77M
        }
503
8.78M
    }
504
8.61M
    return Status::OK();
505
8.61M
}
506
507
bool ColumnReader::_zone_map_match_condition(const ZoneMap& zone_map,
508
1.90M
                                             const AndBlockColumnPredicate* col_predicates) const {
509
1.90M
    if (zone_map.pass_all) {
510
0
        return true;
511
0
    }
512
513
1.90M
    return col_predicates->evaluate_and(zone_map);
514
1.90M
}
515
516
Status ColumnReader::_get_filtered_pages(
517
        const AndBlockColumnPredicate* col_predicates,
518
        const std::vector<std::shared_ptr<const ColumnPredicate>>* delete_predicates,
519
107k
        std::vector<uint32_t>* page_indexes, const ColumnIteratorOptions& iter_opts) {
520
107k
    RETURN_IF_ERROR(_load_zone_map_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
521
522
107k
    const std::vector<ZoneMapPB>& zone_maps = _zone_map_index->page_zone_maps();
523
107k
    size_t page_size = _zone_map_index->num_pages();
524
253k
    for (size_t i = 0; i < page_size; ++i) {
525
146k
        if (zone_maps[i].pass_all()) {
526
66.7k
            page_indexes->push_back(cast_set<uint32_t>(i));
527
79.3k
        } else {
528
79.3k
            segment_v2::ZoneMap zone_map;
529
79.3k
            RETURN_IF_ERROR(ZoneMap::from_proto(zone_maps[i], _data_type, zone_map));
530
79.3k
            if (_zone_map_match_condition(zone_map, col_predicates)) {
531
78.7k
                bool should_read = true;
532
78.7k
                if (delete_predicates != nullptr) {
533
4
                    for (auto del_pred : *delete_predicates) {
534
                        // TODO: Both `min_value` and `max_value` should be 0 or neither should be 0.
535
                        //  So nullable only need to judge once.
536
4
                        if (del_pred->evaluate_del(zone_map)) {
537
1
                            should_read = false;
538
1
                            break;
539
1
                        }
540
4
                    }
541
3
                }
542
78.7k
                if (should_read) {
543
78.7k
                    page_indexes->push_back(cast_set<uint32_t>(i));
544
78.7k
                }
545
78.7k
            }
546
79.3k
        }
547
146k
    }
548
18.4E
    VLOG(1) << "total-pages: " << page_size << " not-filtered-pages: " << page_indexes->size()
549
18.4E
            << " filtered-percent:"
550
18.4E
            << 1.0 - (static_cast<double>(page_indexes->size()) /
551
18.4E
                      (static_cast<double>(page_size) * 1.0));
552
107k
    return Status::OK();
553
107k
}
554
555
Status ColumnReader::_calculate_row_ranges(const std::vector<uint32_t>& page_indexes,
556
                                           RowRanges* row_ranges,
557
107k
                                           const ColumnIteratorOptions& iter_opts) {
558
107k
    row_ranges->clear();
559
107k
    RETURN_IF_ERROR(_load_ordinal_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
560
145k
    for (auto i : page_indexes) {
561
145k
        ordinal_t page_first_id = _ordinal_index->get_first_ordinal(i);
562
145k
        ordinal_t page_last_id = _ordinal_index->get_last_ordinal(i);
563
145k
        RowRanges page_row_ranges(RowRanges::create_single(page_first_id, page_last_id + 1));
564
145k
        RowRanges::ranges_union(*row_ranges, page_row_ranges, row_ranges);
565
145k
    }
566
107k
    return Status::OK();
567
107k
}
568
569
Status ColumnReader::get_row_ranges_by_bloom_filter(const AndBlockColumnPredicate* col_predicates,
570
                                                    RowRanges* row_ranges,
571
99
                                                    const ColumnIteratorOptions& iter_opts) {
572
99
    RETURN_IF_ERROR(_load_ordinal_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
573
99
    RETURN_IF_ERROR(
574
99
            _load_bloom_filter_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
575
99
    RowRanges bf_row_ranges;
576
99
    std::unique_ptr<BloomFilterIndexIterator> bf_iter;
577
99
    RETURN_IF_ERROR(_bloom_filter_index->new_iterator(&bf_iter, iter_opts.stats));
578
99
    size_t range_size = row_ranges->range_size();
579
    // get covered page ids
580
99
    std::set<uint32_t> page_ids;
581
199
    for (int i = 0; i < range_size; ++i) {
582
100
        int64_t from = row_ranges->get_range_from(i);
583
100
        int64_t idx = from;
584
100
        int64_t to = row_ranges->get_range_to(i);
585
100
        auto iter = _ordinal_index->seek_at_or_before(from);
586
226
        while (idx < to && iter.valid()) {
587
126
            page_ids.insert(iter.page_index());
588
126
            idx = iter.last_ordinal() + 1;
589
126
            iter.next();
590
126
        }
591
100
    }
592
125
    for (auto& pid : page_ids) {
593
125
        std::unique_ptr<BloomFilter> bf;
594
125
        RETURN_IF_ERROR(bf_iter->read_bloom_filter(pid, &bf));
595
125
        if (col_predicates->evaluate_and(bf.get())) {
596
22
            bf_row_ranges.add(RowRange(_ordinal_index->get_first_ordinal(pid),
597
22
                                       _ordinal_index->get_last_ordinal(pid) + 1));
598
22
        }
599
125
    }
600
99
    RowRanges::ranges_intersection(*row_ranges, bf_row_ranges, row_ranges);
601
99
    return Status::OK();
602
99
}
603
604
Status ColumnReader::_load_ordinal_index(bool use_page_cache, bool kept_in_memory,
605
1.62M
                                         const ColumnIteratorOptions& iter_opts) {
606
1.62M
    if (!_ordinal_index) {
607
0
        return Status::InternalError("ordinal_index not inited");
608
0
    }
609
1.62M
    return _ordinal_index->load(use_page_cache, kept_in_memory, iter_opts.stats);
610
1.62M
}
611
612
Status ColumnReader::_load_zone_map_index(bool use_page_cache, bool kept_in_memory,
613
107k
                                          const ColumnIteratorOptions& iter_opts) {
614
107k
    if (_zone_map_index != nullptr) {
615
107k
        return _zone_map_index->load(use_page_cache, kept_in_memory, iter_opts.stats);
616
107k
    }
617
18.4E
    return Status::OK();
618
107k
}
619
620
Status ColumnReader::_load_index(const std::shared_ptr<IndexFileReader>& index_file_reader,
621
                                 const TabletIndex* index_meta, const std::string& rowset_id,
622
74.5k
                                 uint32_t segment_id, size_t rows_of_segment) {
623
74.5k
    std::unique_lock<std::shared_mutex> wlock(_load_index_lock);
624
625
74.5k
    if (index_meta == nullptr) {
626
0
        return Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
627
0
                "Failed to load inverted index: index metadata is null");
628
0
    }
629
630
74.5k
    auto it = _index_readers.find(index_meta->index_id());
631
74.5k
    if (it != _index_readers.end()) {
632
0
        return Status::OK();
633
0
    }
634
635
74.5k
    bool should_analyzer =
636
74.5k
            inverted_index::InvertedIndexAnalyzer::should_analyzer(index_meta->properties());
637
638
74.5k
    FieldType type;
639
74.5k
    if (_meta_type == FieldType::OLAP_FIELD_TYPE_ARRAY) {
640
6.41k
        type = _meta_children_column_type;
641
68.1k
    } else {
642
68.1k
        type = _type;
643
68.1k
    }
644
645
74.5k
    if (index_meta->index_type() == IndexType::ANN) {
646
194
        _index_readers[index_meta->index_id()] = std::make_shared<AnnIndexReader>(
647
194
                index_meta, index_file_reader, rowset_id, segment_id, rows_of_segment);
648
194
        return Status::OK();
649
194
    }
650
651
74.3k
    IndexReaderPtr index_reader;
652
653
74.3k
    if (is_string_type(type)) {
654
40.4k
        if (should_analyzer) {
655
23.3k
            try {
656
23.3k
                index_reader = FullTextIndexReader::create_shared(index_meta, index_file_reader);
657
23.3k
            } catch (const CLuceneError& e) {
658
0
                return Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
659
0
                        "create FullTextIndexReader error: {}", e.what());
660
0
            }
661
23.3k
        } else {
662
17.1k
            try {
663
17.1k
                index_reader =
664
17.1k
                        StringTypeInvertedIndexReader::create_shared(index_meta, index_file_reader);
665
17.1k
            } catch (const CLuceneError& e) {
666
0
                return Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
667
0
                        "create StringTypeInvertedIndexReader error: {}", e.what());
668
0
            }
669
17.1k
        }
670
40.4k
    } else if (is_numeric_type(type)) {
671
33.8k
        try {
672
33.8k
            index_reader = BkdIndexReader::create_shared(index_meta, index_file_reader);
673
33.8k
        } catch (const CLuceneError& e) {
674
0
            return Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
675
0
                    "create BkdIndexReader error: {}", e.what());
676
0
        }
677
18.4E
    } else {
678
18.4E
        return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
679
18.4E
                "Field type {} is not supported for inverted index", type);
680
18.4E
    }
681
74.3k
    _index_readers[index_meta->index_id()] = index_reader;
682
74.3k
    return Status::OK();
683
74.3k
}
684
685
82.7k
bool ColumnReader::has_bloom_filter_index(bool ngram) const {
686
82.8k
    if (_bloom_filter_index == nullptr) return false;
687
688
18.4E
    if (ngram) {
689
77
        return _bloom_filter_index->algorithm() == BloomFilterAlgorithmPB::NGRAM_BLOOM_FILTER;
690
18.4E
    } else {
691
18.4E
        return _bloom_filter_index->algorithm() != BloomFilterAlgorithmPB::NGRAM_BLOOM_FILTER;
692
18.4E
    }
693
18.4E
}
694
695
Status ColumnReader::_load_bloom_filter_index(bool use_page_cache, bool kept_in_memory,
696
100
                                              const ColumnIteratorOptions& iter_opts) {
697
100
    if (_bloom_filter_index != nullptr) {
698
100
        return _bloom_filter_index->load(use_page_cache, kept_in_memory, iter_opts.stats);
699
100
    }
700
0
    return Status::OK();
701
100
}
702
703
Status ColumnReader::seek_at_or_before(ordinal_t ordinal, OrdinalPageIndexIterator* iter,
704
1.51M
                                       const ColumnIteratorOptions& iter_opts) {
705
1.51M
    RETURN_IF_ERROR(_load_ordinal_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
706
1.51M
    *iter = _ordinal_index->seek_at_or_before(ordinal);
707
1.51M
    if (!iter->valid()) {
708
0
        return Status::NotFound("Failed to seek to ordinal {}, ", ordinal);
709
0
    }
710
1.51M
    return Status::OK();
711
1.51M
}
712
713
Status ColumnReader::get_ordinal_index_reader(OrdinalIndexReader*& reader,
714
879k
                                              OlapReaderStatistics* index_load_stats) {
715
18.4E
    CHECK(_ordinal_index) << fmt::format("ordinal index is null for column reader of type {}",
716
18.4E
                                         std::to_string(int(_meta_type)));
717
879k
    RETURN_IF_ERROR(
718
879k
            _ordinal_index->load(_use_index_page_cache, _opts.kept_in_memory, index_load_stats));
719
879k
    reader = _ordinal_index.get();
720
879k
    return Status::OK();
721
879k
}
722
723
393k
Status ColumnReader::new_iterator(ColumnIteratorUPtr* iterator, const TabletColumn* tablet_column) {
724
393k
    return new_iterator(iterator, tablet_column, nullptr);
725
393k
}
726
727
Status ColumnReader::new_iterator(ColumnIteratorUPtr* iterator, const TabletColumn* tablet_column,
728
27.1M
                                  const StorageReadOptions* opt) {
729
27.1M
    if (is_empty()) {
730
41.6k
        *iterator = std::make_unique<EmptyFileColumnIterator>();
731
41.6k
        return Status::OK();
732
41.6k
    }
733
27.0M
    if (is_scalar_type(_meta_type)) {
734
26.9M
        if (is_string_type(_meta_type)) {
735
16.2M
            *iterator = std::make_unique<StringFileColumnIterator>(shared_from_this());
736
16.2M
        } else {
737
10.6M
            *iterator = std::make_unique<FileColumnIterator>(shared_from_this());
738
10.6M
        }
739
26.9M
        (*iterator)->set_column_name(tablet_column ? tablet_column->name() : "");
740
26.9M
        return Status::OK();
741
26.9M
    } else {
742
95.5k
        auto type = _meta_type;
743
95.5k
        switch (type) {
744
859
        case FieldType::OLAP_FIELD_TYPE_AGG_STATE: {
745
859
            return new_agg_state_iterator(iterator);
746
0
        }
747
7.84k
        case FieldType::OLAP_FIELD_TYPE_STRUCT: {
748
7.84k
            return new_struct_iterator(iterator, tablet_column);
749
0
        }
750
63.0k
        case FieldType::OLAP_FIELD_TYPE_ARRAY: {
751
63.0k
            return new_array_iterator(iterator, tablet_column);
752
0
        }
753
35.2k
        case FieldType::OLAP_FIELD_TYPE_MAP: {
754
35.2k
            return new_map_iterator(iterator, tablet_column);
755
0
        }
756
0
        default:
757
0
            return Status::NotSupported("unsupported type to create iterator: {}",
758
0
                                        std::to_string(int(type)));
759
95.5k
        }
760
95.5k
    }
761
27.0M
}
762
763
857
Status ColumnReader::new_agg_state_iterator(ColumnIteratorUPtr* iterator) {
764
857
    *iterator = std::make_unique<FileColumnIterator>(shared_from_this());
765
857
    return Status::OK();
766
857
}
767
768
Status ColumnReader::new_array_iterator(ColumnIteratorUPtr* iterator,
769
62.9k
                                        const TabletColumn* tablet_column) {
770
62.9k
    ColumnIteratorUPtr item_iterator;
771
62.9k
    RETURN_IF_ERROR(_sub_readers[0]->new_iterator(
772
62.9k
            &item_iterator, tablet_column && tablet_column->get_subtype_count() > 0
773
62.9k
                                    ? &tablet_column->get_sub_column(0)
774
62.9k
                                    : nullptr));
775
776
62.9k
    item_iterator->set_column_name(tablet_column ? tablet_column->get_sub_column(0).name() : "");
777
778
62.9k
    ColumnIteratorUPtr offset_iterator;
779
62.9k
    RETURN_IF_ERROR(_sub_readers[1]->new_iterator(&offset_iterator, nullptr));
780
62.9k
    auto* file_iter = static_cast<FileColumnIterator*>(offset_iterator.release());
781
62.9k
    OffsetFileColumnIteratorUPtr ofcIter = std::make_unique<OffsetFileColumnIterator>(
782
62.9k
            std::unique_ptr<FileColumnIterator>(file_iter));
783
784
62.9k
    ColumnIteratorUPtr null_iterator;
785
62.9k
    if (is_nullable()) {
786
44.7k
        RETURN_IF_ERROR(_sub_readers[2]->new_iterator(&null_iterator, nullptr));
787
44.7k
    }
788
62.9k
    *iterator = std::make_unique<ArrayFileColumnIterator>(shared_from_this(), std::move(ofcIter),
789
62.9k
                                                          std::move(item_iterator),
790
62.9k
                                                          std::move(null_iterator));
791
62.9k
    return Status::OK();
792
62.9k
}
793
794
Status ColumnReader::new_map_iterator(ColumnIteratorUPtr* iterator,
795
35.2k
                                      const TabletColumn* tablet_column) {
796
35.2k
    ColumnIteratorUPtr key_iterator;
797
35.2k
    RETURN_IF_ERROR(_sub_readers[0]->new_iterator(
798
35.2k
            &key_iterator, tablet_column && tablet_column->get_subtype_count() > 1
799
35.2k
                                   ? &tablet_column->get_sub_column(0)
800
35.2k
                                   : nullptr));
801
35.2k
    key_iterator->set_column_name(tablet_column ? tablet_column->get_sub_column(0).name() : "");
802
35.2k
    ColumnIteratorUPtr val_iterator;
803
35.2k
    RETURN_IF_ERROR(_sub_readers[1]->new_iterator(
804
35.2k
            &val_iterator, tablet_column && tablet_column->get_subtype_count() > 1
805
35.2k
                                   ? &tablet_column->get_sub_column(1)
806
35.2k
                                   : nullptr));
807
35.2k
    val_iterator->set_column_name(tablet_column ? tablet_column->get_sub_column(1).name() : "");
808
35.2k
    ColumnIteratorUPtr offsets_iterator;
809
35.2k
    RETURN_IF_ERROR(_sub_readers[2]->new_iterator(&offsets_iterator, nullptr));
810
35.2k
    auto* file_iter = static_cast<FileColumnIterator*>(offsets_iterator.release());
811
35.2k
    OffsetFileColumnIteratorUPtr ofcIter = std::make_unique<OffsetFileColumnIterator>(
812
35.2k
            std::unique_ptr<FileColumnIterator>(file_iter));
813
814
35.2k
    ColumnIteratorUPtr null_iterator;
815
35.2k
    if (is_nullable()) {
816
15.4k
        RETURN_IF_ERROR(_sub_readers[3]->new_iterator(&null_iterator, nullptr));
817
15.4k
    }
818
35.2k
    *iterator = std::make_unique<MapFileColumnIterator>(
819
35.2k
            shared_from_this(), std::move(null_iterator), std::move(ofcIter),
820
35.2k
            std::move(key_iterator), std::move(val_iterator));
821
35.2k
    return Status::OK();
822
35.2k
}
823
824
Status ColumnReader::new_struct_iterator(ColumnIteratorUPtr* iterator,
825
7.84k
                                         const TabletColumn* tablet_column) {
826
7.84k
    std::vector<ColumnIteratorUPtr> sub_column_iterators;
827
7.84k
    size_t child_size = is_nullable() ? _sub_readers.size() - 1 : _sub_readers.size();
828
7.84k
    size_t tablet_column_size = tablet_column ? tablet_column->get_sub_columns().size() : 0;
829
7.84k
    sub_column_iterators.reserve(child_size);
830
831
34.9k
    for (uint64_t i = 0; i < child_size; i++) {
832
27.0k
        ColumnIteratorUPtr sub_column_iterator;
833
27.0k
        RETURN_IF_ERROR(_sub_readers[i]->new_iterator(
834
27.0k
                &sub_column_iterator, tablet_column ? &tablet_column->get_sub_column(i) : nullptr));
835
27.0k
        sub_column_iterator->set_column_name(tablet_column ? tablet_column->get_sub_column(i).name()
836
27.0k
                                                           : "");
837
27.0k
        sub_column_iterators.emplace_back(std::move(sub_column_iterator));
838
27.0k
    }
839
840
    // create default_iterator for schema-change behavior which increase column
841
9.16k
    for (size_t i = child_size; i < tablet_column_size; i++) {
842
1.31k
        TabletColumn column = tablet_column->get_sub_column(i);
843
1.31k
        ColumnIteratorUPtr it;
844
1.31k
        RETURN_IF_ERROR(Segment::new_default_iterator(column, &it));
845
1.31k
        it->set_column_name(column.name());
846
1.31k
        sub_column_iterators.emplace_back(std::move(it));
847
1.31k
    }
848
849
7.84k
    ColumnIteratorUPtr null_iterator;
850
7.84k
    if (is_nullable()) {
851
7.00k
        RETURN_IF_ERROR(_sub_readers[child_size]->new_iterator(&null_iterator, nullptr));
852
7.00k
    }
853
7.84k
    *iterator = std::make_unique<StructFileColumnIterator>(
854
7.84k
            shared_from_this(), std::move(null_iterator), std::move(sub_column_iterators));
855
7.84k
    return Status::OK();
856
7.84k
}
857
858
Result<TColumnAccessPaths> ColumnIterator::_get_sub_access_paths(
859
117k
        const TColumnAccessPaths& access_paths) {
860
117k
    TColumnAccessPaths sub_access_paths = access_paths;
861
181k
    for (auto it = sub_access_paths.begin(); it != sub_access_paths.end();) {
862
63.3k
        TColumnAccessPath& name_path = *it;
863
63.3k
        if (name_path.data_access_path.path.empty()) {
864
1
            return ResultError(
865
1
                    Status::InternalError("Invalid access path for struct column: path is empty"));
866
1
        }
867
868
63.3k
        if (!StringCaseEqual()(name_path.data_access_path.path[0], _column_name)) {
869
1
            return ResultError(Status::InternalError(
870
1
                    R"(Invalid access path for column: expected name "{}", got "{}")", _column_name,
871
1
                    name_path.data_access_path.path[0]));
872
1
        }
873
874
63.3k
        name_path.data_access_path.path.erase(name_path.data_access_path.path.begin());
875
63.3k
        if (!name_path.data_access_path.path.empty()) {
876
7.00k
            ++it;
877
56.3k
        } else {
878
56.3k
            set_need_to_read();
879
56.3k
            it = sub_access_paths.erase(it);
880
56.3k
        }
881
63.3k
    }
882
117k
    return sub_access_paths;
883
117k
}
884
885
///====================== MapFileColumnIterator ============================////
886
MapFileColumnIterator::MapFileColumnIterator(std::shared_ptr<ColumnReader> reader,
887
                                             ColumnIteratorUPtr null_iterator,
888
                                             OffsetFileColumnIteratorUPtr offsets_iterator,
889
                                             ColumnIteratorUPtr key_iterator,
890
                                             ColumnIteratorUPtr val_iterator)
891
35.2k
        : _map_reader(reader),
892
35.2k
          _offsets_iterator(std::move(offsets_iterator)),
893
35.2k
          _key_iterator(std::move(key_iterator)),
894
35.2k
          _val_iterator(std::move(val_iterator)) {
895
35.2k
    if (_map_reader->is_nullable()) {
896
15.4k
        _null_iterator = std::move(null_iterator);
897
15.4k
    }
898
35.2k
}
899
900
35.1k
Status MapFileColumnIterator::init(const ColumnIteratorOptions& opts) {
901
35.1k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
902
32
        DLOG(INFO) << "Map column iterator column " << _column_name << " skip reading.";
903
32
        return Status::OK();
904
32
    }
905
35.1k
    RETURN_IF_ERROR(_key_iterator->init(opts));
906
35.1k
    RETURN_IF_ERROR(_val_iterator->init(opts));
907
35.1k
    RETURN_IF_ERROR(_offsets_iterator->init(opts));
908
35.1k
    if (_map_reader->is_nullable()) {
909
15.4k
        RETURN_IF_ERROR(_null_iterator->init(opts));
910
15.4k
    }
911
35.1k
    return Status::OK();
912
35.1k
}
913
914
20.2k
Status MapFileColumnIterator::seek_to_ordinal(ordinal_t ord) {
915
20.2k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
916
0
        DLOG(INFO) << "Map column iterator column " << _column_name << " skip reading.";
917
0
        return Status::OK();
918
0
    }
919
920
20.2k
    if (read_null_map_only()) {
921
        // In NULL_MAP_ONLY mode, only seek the null iterator; skip offset/key/val iterators
922
5
        if (_map_reader->is_nullable() && _null_iterator) {
923
5
            RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
924
5
        }
925
5
        return Status::OK();
926
5
    }
927
928
20.2k
    if (_map_reader->is_nullable()) {
929
11.0k
        RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
930
11.0k
    }
931
20.2k
    RETURN_IF_ERROR(_offsets_iterator->seek_to_ordinal(ord));
932
20.2k
    if (read_offset_only()) {
933
        // In OFFSET_ONLY mode, key/value iterators are SKIP_READING, no need to seek them
934
468
        return Status::OK();
935
468
    }
936
    // here to use offset info
937
19.7k
    ordinal_t offset = 0;
938
19.7k
    RETURN_IF_ERROR(_offsets_iterator->_peek_one_offset(&offset));
939
19.7k
    RETURN_IF_ERROR(_key_iterator->seek_to_ordinal(offset));
940
19.7k
    RETURN_IF_ERROR(_val_iterator->seek_to_ordinal(offset));
941
19.7k
    return Status::OK();
942
19.7k
}
943
944
6.15k
Status MapFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
945
6.15k
    RETURN_IF_ERROR(_offsets_iterator->init_prefetcher(params));
946
6.15k
    if (_map_reader->is_nullable()) {
947
4.86k
        RETURN_IF_ERROR(_null_iterator->init_prefetcher(params));
948
4.86k
    }
949
6.15k
    RETURN_IF_ERROR(_key_iterator->init_prefetcher(params));
950
6.15k
    RETURN_IF_ERROR(_val_iterator->init_prefetcher(params));
951
6.15k
    return Status::OK();
952
6.15k
}
953
954
void MapFileColumnIterator::collect_prefetchers(
955
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
956
6.14k
        PrefetcherInitMethod init_method) {
957
6.14k
    _offsets_iterator->collect_prefetchers(prefetchers, init_method);
958
6.14k
    if (_map_reader->is_nullable()) {
959
4.85k
        _null_iterator->collect_prefetchers(prefetchers, init_method);
960
4.85k
    }
961
    // the actual data pages to read of key/value column depends on the read result of offset column,
962
    // so we can't init prefetch blocks according to rowids, just prefetch all data blocks here.
963
6.14k
    _key_iterator->collect_prefetchers(prefetchers, PrefetcherInitMethod::ALL_DATA_BLOCKS);
964
6.14k
    _val_iterator->collect_prefetchers(prefetchers, PrefetcherInitMethod::ALL_DATA_BLOCKS);
965
6.14k
}
966
967
20.2k
Status MapFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
968
20.2k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
969
0
        DLOG(INFO) << "Map column iterator column " << _column_name << " skip reading.";
970
0
        dst->insert_many_defaults(*n);
971
0
        return Status::OK();
972
0
    }
973
974
20.2k
    if (read_null_map_only()) {
975
        // NULL_MAP_ONLY mode: read null map, fill nested ColumnMap with empty defaults
976
5
        DORIS_CHECK(dst->is_nullable());
977
5
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
978
5
        auto null_map_ptr = nullable_col.get_null_map_column_ptr();
979
5
        size_t num_read = *n;
980
5
        if (_null_iterator) {
981
5
            bool null_signs_has_null = false;
982
5
            RETURN_IF_ERROR(
983
5
                    _null_iterator->next_batch(&num_read, null_map_ptr, &null_signs_has_null));
984
5
        } else {
985
            // schema-change: column became nullable but old segment has no null data
986
0
            auto& null_map = assert_cast<ColumnUInt8&, TypeCheckOnRelease::DISABLE>(*null_map_ptr);
987
0
            null_map.insert_many_vals(0, num_read);
988
0
        }
989
5
        DCHECK(num_read == *n);
990
        // fill nested ColumnMap with empty (zero-element) maps
991
5
        auto& column_map = assert_cast<ColumnMap&, TypeCheckOnRelease::DISABLE>(
992
5
                nullable_col.get_nested_column());
993
5
        column_map.insert_many_defaults(num_read);
994
5
        *has_null = true;
995
5
        return Status::OK();
996
5
    }
997
998
20.2k
    auto& column_map = assert_cast<ColumnMap&, TypeCheckOnRelease::DISABLE>(
999
20.2k
            dst->is_nullable() ? static_cast<ColumnNullable&>(*dst).get_nested_column() : *dst);
1000
20.2k
    auto column_offsets_ptr = IColumn::mutate(std::move(column_map.get_offsets_ptr()));
1001
20.2k
    Defer defer_offsets {[&] { column_map.get_offsets_ptr() = std::move(column_offsets_ptr); }};
1002
20.2k
    bool offsets_has_null = false;
1003
20.2k
    ssize_t start = column_offsets_ptr->size();
1004
20.2k
    RETURN_IF_ERROR(_offsets_iterator->next_batch(n, column_offsets_ptr, &offsets_has_null));
1005
20.2k
    if (*n == 0) {
1006
0
        return Status::OK();
1007
0
    }
1008
20.2k
    auto& column_offsets = static_cast<ColumnArray::ColumnOffsets&>(*column_offsets_ptr);
1009
20.2k
    RETURN_IF_ERROR(_offsets_iterator->_calculate_offsets(start, column_offsets));
1010
20.2k
    DCHECK(column_offsets.get_data().back() >= column_offsets.get_data()[start - 1]);
1011
20.2k
    size_t num_items =
1012
20.2k
            column_offsets.get_data().back() - column_offsets.get_data()[start - 1]; // -1 is valid
1013
1014
20.2k
    if (num_items > 0) {
1015
17.1k
        auto key_ptr = IColumn::mutate(std::move(column_map.get_keys_ptr()));
1016
17.1k
        auto val_ptr = IColumn::mutate(std::move(column_map.get_values_ptr()));
1017
17.1k
        Defer defer_keys {[&] { column_map.get_keys_ptr() = std::move(key_ptr); }};
1018
17.1k
        Defer defer_values {[&] { column_map.get_values_ptr() = std::move(val_ptr); }};
1019
17.1k
        if (read_offset_only()) {
1020
            // OFFSET_ONLY mode: skip reading actual key/value data, fill with defaults
1021
468
            key_ptr->insert_many_defaults(num_items);
1022
468
            val_ptr->insert_many_defaults(num_items);
1023
16.7k
        } else {
1024
16.7k
            size_t num_read = num_items;
1025
16.7k
            bool key_has_null = false;
1026
16.7k
            bool val_has_null = false;
1027
16.7k
            RETURN_IF_ERROR(_key_iterator->next_batch(&num_read, key_ptr, &key_has_null));
1028
16.7k
            RETURN_IF_ERROR(_val_iterator->next_batch(&num_read, val_ptr, &val_has_null));
1029
16.7k
            DCHECK(num_read == num_items);
1030
16.7k
        }
1031
17.1k
    }
1032
1033
20.2k
    if (dst->is_nullable()) {
1034
11.0k
        size_t num_read = *n;
1035
11.0k
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1036
        // in not-null to null linked-schemachange mode,
1037
        // actually we do not change dat data include meta in footer,
1038
        // so may dst from changed meta which is nullable but old data is not nullable,
1039
        // if so, we should set null_map to all null by default
1040
11.0k
        if (_null_iterator) {
1041
11.0k
            bool null_signs_has_null = false;
1042
11.0k
            RETURN_IF_ERROR(
1043
11.0k
                    _null_iterator->next_batch(&num_read, null_map_ptr, &null_signs_has_null));
1044
18.4E
        } else {
1045
18.4E
            auto& null_map = assert_cast<ColumnUInt8&, TypeCheckOnRelease::DISABLE>(*null_map_ptr);
1046
18.4E
            null_map.insert_many_vals(0, num_read);
1047
18.4E
        }
1048
11.0k
        DCHECK(num_read == *n);
1049
11.0k
    }
1050
20.2k
    return Status::OK();
1051
20.2k
}
1052
1053
Status MapFileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
1054
16.3k
                                             MutableColumnPtr& dst) {
1055
16.3k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1056
1
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
1057
1
        dst->insert_many_defaults(count);
1058
1
        return Status::OK();
1059
1
    }
1060
1061
16.3k
    if (read_null_map_only()) {
1062
        // NULL_MAP_ONLY mode: read null map by rowids, fill nested ColumnMap with empty defaults
1063
7
        DORIS_CHECK(dst->is_nullable());
1064
7
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
1065
7
        if (_null_iterator) {
1066
7
            auto null_map_ptr = nullable_col.get_null_map_column_ptr();
1067
7
            RETURN_IF_ERROR(_null_iterator->read_by_rowids(rowids, count, null_map_ptr));
1068
7
        } else {
1069
            // schema-change: column became nullable but old segment has no null data
1070
0
            auto null_map_ptr = nullable_col.get_null_map_column_ptr();
1071
0
            auto& null_map = assert_cast<ColumnUInt8&, TypeCheckOnRelease::DISABLE>(*null_map_ptr);
1072
0
            null_map.insert_many_vals(0, count);
1073
0
        }
1074
        // fill nested ColumnMap with empty (zero-element) maps
1075
7
        auto& column_map = assert_cast<ColumnMap&, TypeCheckOnRelease::DISABLE>(
1076
7
                nullable_col.get_nested_column());
1077
7
        column_map.insert_many_defaults(count);
1078
7
        return Status::OK();
1079
7
    }
1080
1081
16.3k
    if (count == 0) {
1082
0
        return Status::OK();
1083
0
    }
1084
    // resolve ColumnMap and nullable wrapper
1085
16.3k
    auto& column_map = assert_cast<ColumnMap&, TypeCheckOnRelease::DISABLE>(
1086
16.3k
            dst->is_nullable() ? static_cast<ColumnNullable&>(*dst).get_nested_column() : *dst);
1087
16.3k
    auto offsets_ptr = IColumn::mutate(std::move(column_map.get_offsets_ptr()));
1088
16.3k
    Defer defer_offsets {[&] { column_map.get_offsets_ptr() = std::move(offsets_ptr); }};
1089
16.3k
    auto& offsets = static_cast<ColumnArray::ColumnOffsets&>(*offsets_ptr);
1090
16.3k
    size_t base = offsets.get_data().empty() ? 0 : offsets.get_data().back();
1091
1092
    // 1. bulk read null-map if nullable
1093
16.3k
    std::vector<uint8_t> null_mask; // 0: not null, 1: null
1094
16.3k
    if (_map_reader->is_nullable()) {
1095
        // For nullable map columns, the destination column must also be nullable.
1096
3.14k
        if (UNLIKELY(!dst->is_nullable())) {
1097
0
            return Status::InternalError(
1098
0
                    "unexpected non-nullable destination column for nullable map reader");
1099
0
        }
1100
3.14k
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1101
3.14k
        size_t null_before = null_map_ptr->size();
1102
3.14k
        RETURN_IF_ERROR(_null_iterator->read_by_rowids(rowids, count, null_map_ptr));
1103
        // extract a light-weight view to decide element reads
1104
3.14k
        auto& null_map_col = assert_cast<ColumnUInt8&>(*null_map_ptr);
1105
3.14k
        null_mask.reserve(count);
1106
56.5k
        for (size_t i = 0; i < count; ++i) {
1107
53.3k
            null_mask.push_back(null_map_col.get_element(null_before + i));
1108
53.3k
        }
1109
13.2k
    } else if (dst->is_nullable()) {
1110
        // in not-null to null linked-schemachange mode,
1111
        // actually we do not change dat data include meta in footer,
1112
        // so may dst from changed meta which is nullable but old data is not nullable,
1113
        // if so, we should set null_map to all null by default
1114
1
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1115
1
        auto& null_map = assert_cast<ColumnUInt8&>(*null_map_ptr);
1116
1
        null_map.insert_many_vals(0, count);
1117
1
    }
1118
1119
    // 2. bulk read start ordinals for requested rows
1120
16.3k
    MutableColumnPtr starts_col = ColumnOffset64::create();
1121
16.3k
    starts_col->reserve(count);
1122
16.3k
    RETURN_IF_ERROR(_offsets_iterator->read_by_rowids(rowids, count, starts_col));
1123
1124
    // 3. bulk read next-start ordinals for rowid+1 (within bounds)
1125
16.3k
    std::vector<rowid_t> next_rowids(count);
1126
3.56M
    for (size_t i = 0; i < count; ++i) {
1127
3.55M
        uint64_t nr = rowids[i] + 1;
1128
3.55M
        next_rowids[i] = nr < _map_reader->num_rows() ? static_cast<rowid_t>(nr)
1129
3.55M
                                                      : static_cast<rowid_t>(0); // placeholder
1130
3.55M
    }
1131
16.3k
    MutableColumnPtr next_starts_col = ColumnOffset64::create();
1132
16.3k
    next_starts_col->reserve(count);
1133
    // read for all; we'll fix out-of-bound cases below
1134
16.3k
    RETURN_IF_ERROR(_offsets_iterator->read_by_rowids(next_rowids.data(), count, next_starts_col));
1135
1136
    // 4. fix next_start for rows whose next_rowid is out-of-bound (rowid == num_rows-1)
1137
3.56M
    for (size_t i = 0; i < count; ++i) {
1138
3.55M
        if (rowids[i] + 1 >= _map_reader->num_rows()) {
1139
            // seek to the last row and consume one to move decoder to end-of-page,
1140
            // then peek page-tail sentinel next_array_item_ordinal as next_start
1141
13.5k
            RETURN_IF_ERROR(_offsets_iterator->seek_to_ordinal(rowids[i]));
1142
13.5k
            size_t one = 1;
1143
13.5k
            bool has_null_unused = false;
1144
13.5k
            MutableColumnPtr tmp = ColumnOffset64::create();
1145
13.5k
            RETURN_IF_ERROR(_offsets_iterator->next_batch(&one, tmp, &has_null_unused));
1146
13.5k
            ordinal_t ns = 0;
1147
13.5k
            RETURN_IF_ERROR(_offsets_iterator->_peek_one_offset(&ns));
1148
            // overwrite with sentinel
1149
13.5k
            assert_cast<ColumnOffset64&, TypeCheckOnRelease::DISABLE>(*next_starts_col)
1150
13.5k
                    .get_data()[i] = ns;
1151
13.5k
        }
1152
3.55M
    }
1153
1154
    // 5. compute sizes and append offsets prefix-sum
1155
16.3k
    auto& starts_data = assert_cast<ColumnOffset64&>(*starts_col).get_data();
1156
16.3k
    auto& next_starts_data = assert_cast<ColumnOffset64&>(*next_starts_col).get_data();
1157
16.3k
    std::vector<size_t> sizes(count, 0);
1158
16.3k
    size_t acc = base;
1159
16.3k
    const auto original_size = offsets.get_data().back();
1160
16.3k
    offsets.get_data().reserve(offsets.get_data().size() + count);
1161
3.55M
    for (size_t i = 0; i < count; ++i) {
1162
3.53M
        size_t sz = static_cast<size_t>(next_starts_data[i] - starts_data[i]);
1163
3.53M
        if (_map_reader->is_nullable() && !null_mask.empty() && null_mask[i]) {
1164
725
            sz = 0; // null rows do not consume elements
1165
725
        }
1166
3.53M
        sizes[i] = sz;
1167
3.53M
        acc += sz;
1168
3.53M
        offsets.get_data().push_back(acc);
1169
3.53M
    }
1170
1171
    // 6. read key/value elements for non-empty sizes
1172
16.3k
    auto keys_ptr = IColumn::mutate(std::move(column_map.get_keys_ptr()));
1173
16.3k
    auto vals_ptr = IColumn::mutate(std::move(column_map.get_values_ptr()));
1174
16.3k
    Defer defer_keys {[&] { column_map.get_keys_ptr() = std::move(keys_ptr); }};
1175
16.3k
    Defer defer_values {[&] { column_map.get_values_ptr() = std::move(vals_ptr); }};
1176
1177
16.3k
    size_t this_run = sizes[0];
1178
16.3k
    auto start_idx = starts_data[0];
1179
16.3k
    auto last_idx = starts_data[0] + this_run;
1180
3.53M
    for (size_t i = 1; i < count; ++i) {
1181
3.52M
        size_t sz = sizes[i];
1182
3.52M
        if (sz == 0) {
1183
146k
            continue;
1184
146k
        }
1185
3.37M
        auto start = static_cast<ordinal_t>(starts_data[i]);
1186
3.37M
        if (start != last_idx) {
1187
469k
            size_t n = this_run;
1188
469k
            bool dummy_has_null = false;
1189
1190
469k
            if (this_run != 0) {
1191
469k
                if (_key_iterator->reading_flag() != ReadingFlag::SKIP_READING) {
1192
469k
                    RETURN_IF_ERROR(_key_iterator->seek_to_ordinal(start_idx));
1193
469k
                    RETURN_IF_ERROR(_key_iterator->next_batch(&n, keys_ptr, &dummy_has_null));
1194
469k
                    DCHECK(n == this_run);
1195
469k
                }
1196
1197
469k
                if (_val_iterator->reading_flag() != ReadingFlag::SKIP_READING) {
1198
467k
                    n = this_run;
1199
467k
                    RETURN_IF_ERROR(_val_iterator->seek_to_ordinal(start_idx));
1200
467k
                    RETURN_IF_ERROR(_val_iterator->next_batch(&n, vals_ptr, &dummy_has_null));
1201
467k
                    DCHECK(n == this_run);
1202
467k
                }
1203
469k
            }
1204
469k
            start_idx = start;
1205
469k
            this_run = sz;
1206
469k
            last_idx = start + sz;
1207
469k
            continue;
1208
469k
        }
1209
1210
2.90M
        this_run += sz;
1211
2.90M
        last_idx += sz;
1212
2.90M
    }
1213
1214
16.3k
    size_t n = this_run;
1215
16.3k
    const size_t total_count = offsets.get_data().back() - original_size;
1216
16.3k
    bool dummy_has_null = false;
1217
16.3k
    if (_key_iterator->reading_flag() != ReadingFlag::SKIP_READING) {
1218
16.3k
        if (this_run != 0) {
1219
7.38k
            RETURN_IF_ERROR(_key_iterator->seek_to_ordinal(start_idx));
1220
7.38k
            RETURN_IF_ERROR(_key_iterator->next_batch(&n, keys_ptr, &dummy_has_null));
1221
7.38k
            DCHECK(n == this_run);
1222
7.38k
        }
1223
16.3k
    } else {
1224
8
        keys_ptr->insert_many_defaults(total_count);
1225
8
    }
1226
1227
16.3k
    if (_val_iterator->reading_flag() != ReadingFlag::SKIP_READING) {
1228
16.3k
        if (this_run != 0) {
1229
7.37k
            n = this_run;
1230
7.37k
            RETURN_IF_ERROR(_val_iterator->seek_to_ordinal(start_idx));
1231
7.37k
            RETURN_IF_ERROR(_val_iterator->next_batch(&n, vals_ptr, &dummy_has_null));
1232
7.37k
            DCHECK(n == this_run);
1233
7.37k
        }
1234
16.3k
    } else {
1235
18
        vals_ptr->insert_many_defaults(total_count);
1236
18
    }
1237
1238
16.3k
    return Status::OK();
1239
16.3k
}
1240
1241
5.72k
void MapFileColumnIterator::set_need_to_read() {
1242
5.72k
    set_reading_flag(ReadingFlag::NEED_TO_READ);
1243
5.72k
    _key_iterator->set_need_to_read();
1244
5.72k
    _val_iterator->set_need_to_read();
1245
5.72k
}
1246
1247
6.95k
void MapFileColumnIterator::remove_pruned_sub_iterators() {
1248
6.95k
    _key_iterator->remove_pruned_sub_iterators();
1249
6.95k
    _val_iterator->remove_pruned_sub_iterators();
1250
6.95k
}
1251
1252
Status MapFileColumnIterator::set_access_paths(const TColumnAccessPaths& all_access_paths,
1253
6.71k
                                               const TColumnAccessPaths& predicate_access_paths) {
1254
6.71k
    if (all_access_paths.empty()) {
1255
1.51k
        return Status::OK();
1256
1.51k
    }
1257
1258
5.19k
    if (!predicate_access_paths.empty()) {
1259
31
        set_reading_flag(ReadingFlag::READING_FOR_PREDICATE);
1260
31
        DLOG(INFO) << "Map column iterator set sub-column " << _column_name
1261
31
                   << " to READING_FOR_PREDICATE";
1262
31
    }
1263
1264
5.19k
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
1265
5.19k
    auto sub_predicate_access_paths = DORIS_TRY(_get_sub_access_paths(predicate_access_paths));
1266
1267
5.19k
    if (sub_all_access_paths.empty()) {
1268
3.99k
        return Status::OK();
1269
3.99k
    }
1270
1271
    // Check for meta-only modes (OFFSET_ONLY or NULL_MAP_ONLY)
1272
1.20k
    _check_and_set_meta_read_mode(sub_all_access_paths);
1273
1.20k
    if (read_offset_only()) {
1274
477
        _key_iterator->set_reading_flag(ReadingFlag::SKIP_READING);
1275
477
        _val_iterator->set_reading_flag(ReadingFlag::SKIP_READING);
1276
477
        DLOG(INFO) << "Map column iterator set column " << _column_name
1277
477
                   << " to OFFSET_ONLY reading mode, key/value columns set to SKIP_READING";
1278
477
        return Status::OK();
1279
477
    }
1280
731
    if (read_null_map_only()) {
1281
12
        _key_iterator->set_reading_flag(ReadingFlag::SKIP_READING);
1282
12
        _val_iterator->set_reading_flag(ReadingFlag::SKIP_READING);
1283
12
        DLOG(INFO) << "Map column iterator set column " << _column_name
1284
12
                   << " to NULL_MAP_ONLY reading mode, key/value columns set to SKIP_READING";
1285
12
        return Status::OK();
1286
12
    }
1287
1288
719
    TColumnAccessPaths key_all_access_paths;
1289
719
    TColumnAccessPaths val_all_access_paths;
1290
719
    TColumnAccessPaths key_predicate_access_paths;
1291
719
    TColumnAccessPaths val_predicate_access_paths;
1292
1293
773
    for (auto paths : sub_all_access_paths) {
1294
773
        if (paths.data_access_path.path[0] == ACCESS_ALL) {
1295
            // ACCESS_ALL means element_at(map, key) style access: the key column must be
1296
            // fully read so that the runtime can match the requested key, while any sub-path
1297
            // qualifiers (e.g. OFFSET) apply only to the value column.
1298
            // For key: create a path with just the column name (= full data access).
1299
197
            TColumnAccessPath key_path;
1300
197
            key_path.__set_type(paths.type);
1301
197
            TDataAccessPath key_data_path;
1302
197
            key_data_path.__set_path({_key_iterator->column_name()});
1303
197
            key_path.__set_data_access_path(key_data_path);
1304
197
            key_all_access_paths.emplace_back(std::move(key_path));
1305
            // For value: pass the full sub-path so qualifiers like OFFSET propagate.
1306
197
            paths.data_access_path.path[0] = _val_iterator->column_name();
1307
197
            val_all_access_paths.emplace_back(paths);
1308
576
        } else if (paths.data_access_path.path[0] == ACCESS_MAP_KEYS) {
1309
293
            paths.data_access_path.path[0] = _key_iterator->column_name();
1310
293
            key_all_access_paths.emplace_back(paths);
1311
293
        } else if (paths.data_access_path.path[0] == ACCESS_MAP_VALUES) {
1312
283
            paths.data_access_path.path[0] = _val_iterator->column_name();
1313
283
            val_all_access_paths.emplace_back(paths);
1314
283
        }
1315
773
    }
1316
719
    const auto need_read_keys = !key_all_access_paths.empty();
1317
719
    const auto need_read_values = !val_all_access_paths.empty();
1318
1319
719
    for (auto paths : sub_predicate_access_paths) {
1320
19
        if (paths.data_access_path.path[0] == ACCESS_ALL) {
1321
            // Same logic as above: key needs full data, value gets the sub-path.
1322
19
            TColumnAccessPath key_path;
1323
19
            key_path.__set_type(paths.type);
1324
19
            TDataAccessPath key_data_path;
1325
19
            key_data_path.__set_path({_key_iterator->column_name()});
1326
19
            key_path.__set_data_access_path(key_data_path);
1327
19
            key_predicate_access_paths.emplace_back(std::move(key_path));
1328
19
            paths.data_access_path.path[0] = _val_iterator->column_name();
1329
19
            val_predicate_access_paths.emplace_back(paths);
1330
19
        } else if (paths.data_access_path.path[0] == ACCESS_MAP_KEYS) {
1331
0
            paths.data_access_path.path[0] = _key_iterator->column_name();
1332
0
            key_predicate_access_paths.emplace_back(paths);
1333
0
        } else if (paths.data_access_path.path[0] == ACCESS_MAP_VALUES) {
1334
0
            paths.data_access_path.path[0] = _val_iterator->column_name();
1335
0
            val_predicate_access_paths.emplace_back(paths);
1336
0
        }
1337
19
    }
1338
1339
719
    if (need_read_keys) {
1340
488
        _key_iterator->set_reading_flag(ReadingFlag::NEED_TO_READ);
1341
488
        RETURN_IF_ERROR(
1342
488
                _key_iterator->set_access_paths(key_all_access_paths, key_predicate_access_paths));
1343
488
    } else {
1344
231
        _key_iterator->set_reading_flag(ReadingFlag::SKIP_READING);
1345
231
        DLOG(INFO) << "Map column iterator set key column to SKIP_READING";
1346
231
    }
1347
1348
719
    if (need_read_values) {
1349
478
        _val_iterator->set_reading_flag(ReadingFlag::NEED_TO_READ);
1350
478
        RETURN_IF_ERROR(
1351
478
                _val_iterator->set_access_paths(val_all_access_paths, val_predicate_access_paths));
1352
478
    } else {
1353
241
        _val_iterator->set_reading_flag(ReadingFlag::SKIP_READING);
1354
241
        DLOG(INFO) << "Map column iterator set value column to SKIP_READING";
1355
241
    }
1356
719
    return Status::OK();
1357
719
}
1358
1359
////////////////////////////////////////////////////////////////////////////////
1360
1361
StructFileColumnIterator::StructFileColumnIterator(
1362
        std::shared_ptr<ColumnReader> reader, ColumnIteratorUPtr null_iterator,
1363
        std::vector<ColumnIteratorUPtr>&& sub_column_iterators)
1364
7.85k
        : _struct_reader(reader), _sub_column_iterators(std::move(sub_column_iterators)) {
1365
7.85k
    if (_struct_reader->is_nullable()) {
1366
7.01k
        _null_iterator = std::move(null_iterator);
1367
7.01k
    }
1368
7.85k
}
1369
1370
7.82k
Status StructFileColumnIterator::init(const ColumnIteratorOptions& opts) {
1371
7.82k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1372
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1373
0
        return Status::OK();
1374
0
    }
1375
1376
27.4k
    for (auto& column_iterator : _sub_column_iterators) {
1377
27.4k
        RETURN_IF_ERROR(column_iterator->init(opts));
1378
27.4k
    }
1379
7.82k
    if (_struct_reader->is_nullable()) {
1380
7.01k
        RETURN_IF_ERROR(_null_iterator->init(opts));
1381
7.01k
    }
1382
7.82k
    return Status::OK();
1383
7.82k
}
1384
1385
4.54k
Status StructFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
1386
4.54k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1387
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1388
0
        dst->insert_many_defaults(*n);
1389
0
        return Status::OK();
1390
0
    }
1391
1392
4.54k
    if (read_null_map_only()) {
1393
        // NULL_MAP_ONLY mode: read null map, fill nested ColumnStruct with empty defaults
1394
2
        DORIS_CHECK(dst->is_nullable());
1395
2
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
1396
2
        auto null_map_ptr = nullable_col.get_null_map_column_ptr();
1397
2
        size_t num_read = *n;
1398
2
        if (_null_iterator) {
1399
2
            bool null_signs_has_null = false;
1400
2
            RETURN_IF_ERROR(
1401
2
                    _null_iterator->next_batch(&num_read, null_map_ptr, &null_signs_has_null));
1402
2
        } else {
1403
            // schema-change: column became nullable but old segment has no null data
1404
0
            auto& null_map = assert_cast<ColumnUInt8&, TypeCheckOnRelease::DISABLE>(*null_map_ptr);
1405
0
            null_map.insert_many_vals(0, num_read);
1406
0
        }
1407
2
        DCHECK(num_read == *n);
1408
        // fill nested ColumnStruct with defaults to maintain consistent column sizes
1409
2
        auto& column_struct = assert_cast<ColumnStruct&, TypeCheckOnRelease::DISABLE>(
1410
2
                nullable_col.get_nested_column());
1411
2
        column_struct.insert_many_defaults(num_read);
1412
2
        *has_null = true;
1413
2
        return Status::OK();
1414
2
    }
1415
1416
4.54k
    auto& column_struct = assert_cast<ColumnStruct&, TypeCheckOnRelease::DISABLE>(
1417
4.54k
            dst->is_nullable() ? static_cast<ColumnNullable&>(*dst).get_nested_column() : *dst);
1418
19.1k
    for (size_t i = 0; i < column_struct.tuple_size(); i++) {
1419
14.5k
        size_t num_read = *n;
1420
14.5k
        auto sub_column_ptr = IColumn::mutate(std::move(column_struct.get_column_ptr(i)));
1421
14.5k
        Defer defer_sub_column {
1422
14.5k
                [&] { column_struct.get_column_ptr(i) = std::move(sub_column_ptr); }};
1423
14.5k
        bool column_has_null = false;
1424
14.5k
        RETURN_IF_ERROR(
1425
14.5k
                _sub_column_iterators[i]->next_batch(&num_read, sub_column_ptr, &column_has_null));
1426
14.5k
        DCHECK(num_read == *n);
1427
14.5k
    }
1428
1429
4.54k
    if (dst->is_nullable()) {
1430
4.23k
        size_t num_read = *n;
1431
4.23k
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1432
        // in not-null to null linked-schemachange mode,
1433
        // actually we do not change dat data include meta in footer,
1434
        // so may dst from changed meta which is nullable but old data is not nullable,
1435
        // if so, we should set null_map to all null by default
1436
4.23k
        if (_null_iterator) {
1437
4.14k
            bool null_signs_has_null = false;
1438
4.14k
            RETURN_IF_ERROR(
1439
4.14k
                    _null_iterator->next_batch(&num_read, null_map_ptr, &null_signs_has_null));
1440
4.14k
        } else {
1441
89
            auto& null_map = assert_cast<ColumnUInt8&, TypeCheckOnRelease::DISABLE>(*null_map_ptr);
1442
89
            null_map.insert_many_vals(0, num_read);
1443
89
        }
1444
4.23k
        DCHECK(num_read == *n);
1445
4.23k
    }
1446
1447
4.54k
    return Status::OK();
1448
4.54k
}
1449
1450
4.54k
Status StructFileColumnIterator::seek_to_ordinal(ordinal_t ord) {
1451
4.54k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1452
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1453
0
        return Status::OK();
1454
0
    }
1455
1456
4.54k
    if (read_null_map_only()) {
1457
        // In NULL_MAP_ONLY mode, only seek the null iterator; skip all sub-column iterators
1458
2
        if (_struct_reader->is_nullable() && _null_iterator) {
1459
2
            RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
1460
2
        }
1461
2
        return Status::OK();
1462
2
    }
1463
1464
14.5k
    for (auto& column_iterator : _sub_column_iterators) {
1465
14.5k
        RETURN_IF_ERROR(column_iterator->seek_to_ordinal(ord));
1466
14.5k
    }
1467
4.54k
    if (_struct_reader->is_nullable()) {
1468
4.14k
        RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
1469
4.14k
    }
1470
4.54k
    return Status::OK();
1471
4.54k
}
1472
1473
3.39k
Status StructFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
1474
9.79k
    for (auto& column_iterator : _sub_column_iterators) {
1475
9.79k
        RETURN_IF_ERROR(column_iterator->init_prefetcher(params));
1476
9.79k
    }
1477
3.39k
    if (_struct_reader->is_nullable()) {
1478
3.04k
        RETURN_IF_ERROR(_null_iterator->init_prefetcher(params));
1479
3.04k
    }
1480
3.39k
    return Status::OK();
1481
3.39k
}
1482
1483
void StructFileColumnIterator::collect_prefetchers(
1484
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
1485
3.39k
        PrefetcherInitMethod init_method) {
1486
9.79k
    for (auto& column_iterator : _sub_column_iterators) {
1487
9.79k
        column_iterator->collect_prefetchers(prefetchers, init_method);
1488
9.79k
    }
1489
3.39k
    if (_struct_reader->is_nullable()) {
1490
3.03k
        _null_iterator->collect_prefetchers(prefetchers, init_method);
1491
3.03k
    }
1492
3.39k
}
1493
1494
Status StructFileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
1495
2.65k
                                                MutableColumnPtr& dst) {
1496
2.65k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1497
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1498
0
        dst->insert_many_defaults(count);
1499
0
        return Status::OK();
1500
0
    }
1501
1502
2.65k
    if (count == 0) {
1503
0
        return Status::OK();
1504
0
    }
1505
1506
2.65k
    size_t this_run = 1;
1507
2.65k
    auto start_idx = rowids[0];
1508
2.65k
    auto last_idx = rowids[0];
1509
2.75k
    for (size_t i = 1; i < count; ++i) {
1510
96
        if (last_idx == rowids[i] - 1) {
1511
92
            last_idx = rowids[i];
1512
92
            this_run++;
1513
92
            continue;
1514
92
        }
1515
4
        RETURN_IF_ERROR(seek_to_ordinal(start_idx));
1516
4
        size_t num_read = this_run;
1517
4
        RETURN_IF_ERROR(next_batch(&num_read, dst));
1518
4
        DCHECK_EQ(num_read, this_run);
1519
1520
4
        start_idx = rowids[i];
1521
4
        last_idx = rowids[i];
1522
4
        this_run = 1;
1523
4
    }
1524
1525
2.65k
    RETURN_IF_ERROR(seek_to_ordinal(start_idx));
1526
2.65k
    size_t num_read = this_run;
1527
2.65k
    RETURN_IF_ERROR(next_batch(&num_read, dst));
1528
2.65k
    DCHECK_EQ(num_read, this_run);
1529
2.65k
    return Status::OK();
1530
2.65k
}
1531
1532
6.90k
void StructFileColumnIterator::set_need_to_read() {
1533
6.90k
    set_reading_flag(ReadingFlag::NEED_TO_READ);
1534
24.9k
    for (auto& sub_iterator : _sub_column_iterators) {
1535
24.9k
        sub_iterator->set_need_to_read();
1536
24.9k
    }
1537
6.90k
}
1538
1539
7.02k
void StructFileColumnIterator::remove_pruned_sub_iterators() {
1540
33.0k
    for (auto it = _sub_column_iterators.begin(); it != _sub_column_iterators.end();) {
1541
26.0k
        auto& sub_iterator = *it;
1542
26.0k
        if (sub_iterator->reading_flag() == ReadingFlag::SKIP_READING) {
1543
838
            DLOG(INFO) << "Struct column iterator remove pruned sub-column "
1544
838
                       << sub_iterator->column_name();
1545
838
            it = _sub_column_iterators.erase(it);
1546
25.1k
        } else {
1547
25.1k
            sub_iterator->remove_pruned_sub_iterators();
1548
25.1k
            ++it;
1549
25.1k
        }
1550
26.0k
    }
1551
7.02k
}
1552
1553
Status StructFileColumnIterator::set_access_paths(
1554
        const TColumnAccessPaths& all_access_paths,
1555
6.47k
        const TColumnAccessPaths& predicate_access_paths) {
1556
6.47k
    if (all_access_paths.empty()) {
1557
1.87k
        return Status::OK();
1558
1.87k
    }
1559
1560
4.60k
    if (!predicate_access_paths.empty()) {
1561
61
        set_reading_flag(ReadingFlag::READING_FOR_PREDICATE);
1562
61
        DLOG(INFO) << "Struct column iterator set sub-column " << _column_name
1563
61
                   << " to READING_FOR_PREDICATE";
1564
61
    }
1565
4.60k
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
1566
4.60k
    auto sub_predicate_access_paths = DORIS_TRY(_get_sub_access_paths(predicate_access_paths));
1567
1568
    // Check for NULL_MAP_ONLY mode: only read null map, skip all sub-columns
1569
4.60k
    _check_and_set_meta_read_mode(sub_all_access_paths);
1570
4.60k
    if (read_null_map_only()) {
1571
6
        for (auto& sub_iterator : _sub_column_iterators) {
1572
6
            sub_iterator->set_reading_flag(ReadingFlag::SKIP_READING);
1573
6
        }
1574
3
        DLOG(INFO) << "Struct column iterator set column " << _column_name
1575
3
                   << " to NULL_MAP_ONLY reading mode, all sub-columns set to SKIP_READING";
1576
3
        return Status::OK();
1577
3
    }
1578
1579
4.59k
    const auto no_sub_column_to_skip = sub_all_access_paths.empty();
1580
4.59k
    const auto no_predicate_sub_column = sub_predicate_access_paths.empty();
1581
1582
20.5k
    for (auto& sub_iterator : _sub_column_iterators) {
1583
20.5k
        const auto name = sub_iterator->column_name();
1584
20.5k
        bool need_to_read = no_sub_column_to_skip;
1585
20.5k
        TColumnAccessPaths sub_all_access_paths_of_this;
1586
20.5k
        if (!need_to_read) {
1587
1.35k
            for (const auto& paths : sub_all_access_paths) {
1588
1.35k
                if (paths.data_access_path.path[0] == name) {
1589
220
                    sub_all_access_paths_of_this.emplace_back(paths);
1590
220
                }
1591
1.35k
            }
1592
1.05k
            need_to_read = !sub_all_access_paths_of_this.empty();
1593
1.05k
        }
1594
1595
20.5k
        if (!need_to_read) {
1596
835
            set_reading_flag(ReadingFlag::SKIP_READING);
1597
835
            sub_iterator->set_reading_flag(ReadingFlag::SKIP_READING);
1598
835
            DLOG(INFO) << "Struct column iterator set sub-column " << name << " to SKIP_READING";
1599
835
            continue;
1600
835
        }
1601
19.6k
        set_reading_flag(ReadingFlag::NEED_TO_READ);
1602
19.6k
        sub_iterator->set_reading_flag(ReadingFlag::NEED_TO_READ);
1603
1604
19.6k
        TColumnAccessPaths sub_predicate_access_paths_of_this;
1605
1606
19.6k
        if (!no_predicate_sub_column) {
1607
59
            for (const auto& paths : sub_predicate_access_paths) {
1608
59
                if (StringCaseEqual()(paths.data_access_path.path[0], name)) {
1609
56
                    sub_predicate_access_paths_of_this.emplace_back(paths);
1610
56
                }
1611
59
            }
1612
59
        }
1613
1614
19.6k
        RETURN_IF_ERROR(sub_iterator->set_access_paths(sub_all_access_paths_of_this,
1615
19.6k
                                                       sub_predicate_access_paths_of_this));
1616
19.6k
    }
1617
4.59k
    return Status::OK();
1618
4.59k
}
1619
1620
////////////////////////////////////////////////////////////////////////////////
1621
97.9k
Status OffsetFileColumnIterator::init(const ColumnIteratorOptions& opts) {
1622
97.9k
    RETURN_IF_ERROR(_offset_iterator->init(opts));
1623
    // allocate peek tmp column once
1624
97.9k
    _peek_tmp_col = ColumnOffset64::create();
1625
97.9k
    return Status::OK();
1626
97.9k
}
1627
1628
158k
Status OffsetFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
1629
158k
    RETURN_IF_ERROR(_offset_iterator->next_batch(n, dst, has_null));
1630
158k
    return Status::OK();
1631
158k
}
1632
1633
301k
Status OffsetFileColumnIterator::_peek_one_offset(ordinal_t* offset) {
1634
301k
    if (_offset_iterator->get_current_page()->has_remaining()) {
1635
215k
        PageDecoder* offset_page_decoder = _offset_iterator->get_current_page()->data_decoder.get();
1636
215k
        size_t n = 1;
1637
215k
        _peek_tmp_col->clear();
1638
215k
        RETURN_IF_ERROR(offset_page_decoder->peek_next_batch(&n, _peek_tmp_col)); // not null
1639
215k
        DCHECK(_peek_tmp_col->size() == 1);
1640
215k
        *offset =
1641
215k
                assert_cast<const ColumnOffset64*, TypeCheckOnRelease::DISABLE>(_peek_tmp_col.get())
1642
215k
                        ->get_element(0);
1643
215k
    } else {
1644
85.6k
        *offset = _offset_iterator->get_current_page()->next_array_item_ordinal;
1645
85.6k
    }
1646
301k
    return Status::OK();
1647
301k
}
1648
1649
51.3k
Status OffsetFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
1650
51.3k
    return _offset_iterator->init_prefetcher(params);
1651
51.3k
}
1652
1653
void OffsetFileColumnIterator::collect_prefetchers(
1654
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
1655
51.2k
        PrefetcherInitMethod init_method) {
1656
51.2k
    _offset_iterator->collect_prefetchers(prefetchers, init_method);
1657
51.2k
}
1658
1659
/**
1660
 *  first_storage_offset read from page should smaller than next_storage_offset which here call _peek_one_offset from page,
1661
    and first_column_offset is keep in memory data which is different dimension with (first_storage_offset and next_storage_offset)
1662
     eg. step1. read page: first_storage_offset = 16382
1663
         step2. read page below with _peek_one_offset(&last_offset): last_offset = 16387
1664
         step3. first_offset = 126 which is calculate in column offsets
1665
         for loop column offsets element in size
1666
            we can calculate from first_storage_offset to next_storage_offset one by one to fill with offsets_data in memory column offsets
1667
 * @param start
1668
 * @param column_offsets
1669
 * @return
1670
 */
1671
Status OffsetFileColumnIterator::_calculate_offsets(ssize_t start,
1672
144k
                                                    ColumnArray::ColumnOffsets& column_offsets) {
1673
144k
    ordinal_t next_storage_offset = 0;
1674
144k
    RETURN_IF_ERROR(_peek_one_offset(&next_storage_offset));
1675
1676
    // calculate real offsets
1677
144k
    auto& offsets_data = column_offsets.get_data();
1678
144k
    ordinal_t first_column_offset = offsets_data[start - 1]; // -1 is valid
1679
144k
    ordinal_t first_storage_offset = offsets_data[start];
1680
144k
    DCHECK(next_storage_offset >= first_storage_offset);
1681
13.0M
    for (ssize_t i = start; i < offsets_data.size() - 1; ++i) {
1682
12.8M
        offsets_data[i] = first_column_offset + (offsets_data[i + 1] - first_storage_offset);
1683
12.8M
    }
1684
    // last offset
1685
144k
    offsets_data[offsets_data.size() - 1] =
1686
144k
            first_column_offset + (next_storage_offset - first_storage_offset);
1687
144k
    return Status::OK();
1688
144k
}
1689
1690
////////////////////////////////////////////////////////////////////////////////
1691
ArrayFileColumnIterator::ArrayFileColumnIterator(std::shared_ptr<ColumnReader> reader,
1692
                                                 OffsetFileColumnIteratorUPtr offset_reader,
1693
                                                 ColumnIteratorUPtr item_iterator,
1694
                                                 ColumnIteratorUPtr null_iterator)
1695
62.9k
        : _array_reader(reader),
1696
62.9k
          _offset_iterator(std::move(offset_reader)),
1697
62.9k
          _item_iterator(std::move(item_iterator)) {
1698
62.9k
    if (_array_reader->is_nullable()) {
1699
44.6k
        _null_iterator = std::move(null_iterator);
1700
44.6k
    }
1701
62.9k
}
1702
1703
62.8k
Status ArrayFileColumnIterator::init(const ColumnIteratorOptions& opts) {
1704
62.8k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1705
56
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip readking.";
1706
56
        return Status::OK();
1707
56
    }
1708
1709
62.7k
    RETURN_IF_ERROR(_offset_iterator->init(opts));
1710
62.7k
    RETURN_IF_ERROR(_item_iterator->init(opts));
1711
62.7k
    if (_array_reader->is_nullable()) {
1712
44.5k
        RETURN_IF_ERROR(_null_iterator->init(opts));
1713
44.5k
    }
1714
62.7k
    return Status::OK();
1715
62.7k
}
1716
1717
124k
Status ArrayFileColumnIterator::_seek_by_offsets(ordinal_t ord) {
1718
124k
    if (read_offset_only()) {
1719
        // In OFFSET_ONLY mode, item iterator is SKIP_READING, no need to seek it
1720
1.19k
        return Status::OK();
1721
1.19k
    }
1722
    // using offsets info
1723
123k
    ordinal_t offset = 0;
1724
123k
    RETURN_IF_ERROR(_offset_iterator->_peek_one_offset(&offset));
1725
123k
    RETURN_IF_ERROR(_item_iterator->seek_to_ordinal(offset));
1726
123k
    return Status::OK();
1727
123k
}
1728
1729
124k
Status ArrayFileColumnIterator::seek_to_ordinal(ordinal_t ord) {
1730
124k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1731
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip reading.";
1732
0
        return Status::OK();
1733
0
    }
1734
1735
124k
    if (read_null_map_only()) {
1736
        // In NULL_MAP_ONLY mode, only seek the null iterator; skip offset and item iterators
1737
2
        if (_array_reader->is_nullable() && _null_iterator) {
1738
2
            RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
1739
2
        }
1740
2
        return Status::OK();
1741
2
    }
1742
1743
124k
    RETURN_IF_ERROR(_offset_iterator->seek_to_ordinal(ord));
1744
124k
    if (_array_reader->is_nullable()) {
1745
105k
        RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
1746
105k
    }
1747
124k
    return _seek_by_offsets(ord);
1748
124k
}
1749
1750
124k
Status ArrayFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
1751
124k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1752
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip reading.";
1753
0
        dst->insert_many_defaults(*n);
1754
0
        return Status::OK();
1755
0
    }
1756
1757
124k
    if (read_null_map_only()) {
1758
        // NULL_MAP_ONLY mode: read null map, fill nested ColumnArray with empty defaults
1759
2
        DORIS_CHECK(dst->is_nullable());
1760
2
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
1761
2
        auto null_map_ptr = nullable_col.get_null_map_column_ptr();
1762
2
        size_t num_read = *n;
1763
2
        if (_null_iterator) {
1764
2
            bool null_signs_has_null = false;
1765
2
            RETURN_IF_ERROR(
1766
2
                    _null_iterator->next_batch(&num_read, null_map_ptr, &null_signs_has_null));
1767
2
        } else {
1768
            // schema-change: column became nullable but old segment has no null data
1769
0
            auto& null_map = assert_cast<ColumnUInt8&, TypeCheckOnRelease::DISABLE>(*null_map_ptr);
1770
0
            null_map.insert_many_vals(0, num_read);
1771
0
        }
1772
2
        DCHECK(num_read == *n);
1773
        // fill nested ColumnArray with empty (zero-length) arrays
1774
2
        auto& column_array = assert_cast<ColumnArray&, TypeCheckOnRelease::DISABLE>(
1775
2
                nullable_col.get_nested_column());
1776
2
        column_array.insert_many_defaults(num_read);
1777
2
        *has_null = true;
1778
2
        return Status::OK();
1779
2
    }
1780
1781
124k
    auto& column_array = assert_cast<ColumnArray&, TypeCheckOnRelease::DISABLE>(
1782
124k
            dst->is_nullable() ? static_cast<ColumnNullable&>(*dst).get_nested_column() : *dst);
1783
1784
124k
    bool offsets_has_null = false;
1785
124k
    auto column_offsets_ptr = IColumn::mutate(std::move(column_array.get_offsets_ptr()));
1786
124k
    Defer defer_offsets {[&] { column_array.get_offsets_ptr() = std::move(column_offsets_ptr); }};
1787
124k
    ssize_t start = column_offsets_ptr->size();
1788
124k
    RETURN_IF_ERROR(_offset_iterator->next_batch(n, column_offsets_ptr, &offsets_has_null));
1789
124k
    if (*n == 0) {
1790
0
        return Status::OK();
1791
0
    }
1792
124k
    auto& column_offsets = static_cast<ColumnArray::ColumnOffsets&>(*column_offsets_ptr);
1793
124k
    RETURN_IF_ERROR(_offset_iterator->_calculate_offsets(start, column_offsets));
1794
124k
    size_t num_items =
1795
124k
            column_offsets.get_data().back() - column_offsets.get_data()[start - 1]; // -1 is valid
1796
124k
    if (num_items > 0) {
1797
89.1k
        auto column_items_ptr = IColumn::mutate(std::move(column_array.get_data_ptr()));
1798
89.1k
        Defer defer_items {[&] { column_array.get_data_ptr() = std::move(column_items_ptr); }};
1799
89.1k
        if (read_offset_only()) {
1800
            // OFFSET_ONLY mode: skip reading actual item data, fill with defaults
1801
1.03k
            column_items_ptr->insert_many_defaults(num_items);
1802
88.0k
        } else {
1803
88.0k
            size_t num_read = num_items;
1804
88.0k
            bool items_has_null = false;
1805
88.0k
            RETURN_IF_ERROR(
1806
88.0k
                    _item_iterator->next_batch(&num_read, column_items_ptr, &items_has_null));
1807
88.0k
            DCHECK(num_read == num_items);
1808
88.0k
        }
1809
89.1k
    }
1810
1811
124k
    if (dst->is_nullable()) {
1812
105k
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1813
105k
        size_t num_read = *n;
1814
        // in not-null to null linked-schemachange mode,
1815
        // actually we do not change dat data include meta in footer,
1816
        // so may dst from changed meta which is nullable but old data is not nullable,
1817
        // if so, we should set null_map to all null by default
1818
105k
        if (_null_iterator) {
1819
105k
            bool null_signs_has_null = false;
1820
105k
            RETURN_IF_ERROR(
1821
105k
                    _null_iterator->next_batch(&num_read, null_map_ptr, &null_signs_has_null));
1822
18.4E
        } else {
1823
18.4E
            auto& null_map = assert_cast<ColumnUInt8&, TypeCheckOnRelease::DISABLE>(*null_map_ptr);
1824
18.4E
            null_map.insert_many_vals(0, num_read);
1825
18.4E
        }
1826
105k
        DCHECK(num_read == *n);
1827
105k
    }
1828
1829
124k
    return Status::OK();
1830
124k
}
1831
1832
45.2k
Status ArrayFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
1833
45.2k
    RETURN_IF_ERROR(_offset_iterator->init_prefetcher(params));
1834
45.2k
    RETURN_IF_ERROR(_item_iterator->init_prefetcher(params));
1835
45.2k
    if (_array_reader->is_nullable()) {
1836
28.7k
        RETURN_IF_ERROR(_null_iterator->init_prefetcher(params));
1837
28.7k
    }
1838
45.2k
    return Status::OK();
1839
45.2k
}
1840
1841
void ArrayFileColumnIterator::collect_prefetchers(
1842
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
1843
45.0k
        PrefetcherInitMethod init_method) {
1844
45.0k
    _offset_iterator->collect_prefetchers(prefetchers, init_method);
1845
    // the actual data pages to read of item column depends on the read result of offset column,
1846
    // so we can't init prefetch blocks according to rowids, just prefetch all data blocks here.
1847
45.0k
    _item_iterator->collect_prefetchers(prefetchers, PrefetcherInitMethod::ALL_DATA_BLOCKS);
1848
45.0k
    if (_array_reader->is_nullable()) {
1849
28.6k
        _null_iterator->collect_prefetchers(prefetchers, init_method);
1850
28.6k
    }
1851
45.0k
}
1852
1853
Status ArrayFileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
1854
31.1k
                                               MutableColumnPtr& dst) {
1855
31.1k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
1856
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip reading.";
1857
0
        dst->insert_many_defaults(count);
1858
0
        return Status::OK();
1859
0
    }
1860
1861
129k
    for (size_t i = 0; i < count; ++i) {
1862
        // TODO(cambyszju): now read array one by one, need optimize later
1863
97.9k
        RETURN_IF_ERROR(seek_to_ordinal(rowids[i]));
1864
97.9k
        size_t num_read = 1;
1865
97.9k
        RETURN_IF_ERROR(next_batch(&num_read, dst));
1866
97.9k
    }
1867
31.1k
    return Status::OK();
1868
31.1k
}
1869
1870
49.3k
void ArrayFileColumnIterator::set_need_to_read() {
1871
49.3k
    set_reading_flag(ReadingFlag::NEED_TO_READ);
1872
49.3k
    _item_iterator->set_need_to_read();
1873
49.3k
}
1874
1875
50.9k
void ArrayFileColumnIterator::remove_pruned_sub_iterators() {
1876
50.9k
    _item_iterator->remove_pruned_sub_iterators();
1877
50.9k
}
1878
1879
Status ArrayFileColumnIterator::set_access_paths(const TColumnAccessPaths& all_access_paths,
1880
50.2k
                                                 const TColumnAccessPaths& predicate_access_paths) {
1881
50.2k
    if (all_access_paths.empty()) {
1882
1.75k
        return Status::OK();
1883
1.75k
    }
1884
1885
48.4k
    if (!predicate_access_paths.empty()) {
1886
3.23k
        set_reading_flag(ReadingFlag::READING_FOR_PREDICATE);
1887
3.23k
        DLOG(INFO) << "Array column iterator set sub-column " << _column_name
1888
3.23k
                   << " to READING_FOR_PREDICATE";
1889
3.23k
    }
1890
1891
48.4k
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
1892
48.4k
    auto sub_predicate_access_paths = DORIS_TRY(_get_sub_access_paths(predicate_access_paths));
1893
1894
    // Check for meta-only modes (OFFSET_ONLY or NULL_MAP_ONLY)
1895
48.4k
    _check_and_set_meta_read_mode(sub_all_access_paths);
1896
48.4k
    if (read_offset_only()) {
1897
1.16k
        _item_iterator->set_reading_flag(ReadingFlag::SKIP_READING);
1898
1.16k
        DLOG(INFO) << "Array column iterator set column " << _column_name
1899
1.16k
                   << " to OFFSET_ONLY reading mode, item column set to SKIP_READING";
1900
1.16k
        return Status::OK();
1901
1.16k
    }
1902
47.2k
    if (read_null_map_only()) {
1903
12
        _item_iterator->set_reading_flag(ReadingFlag::SKIP_READING);
1904
12
        DLOG(INFO) << "Array column iterator set column " << _column_name
1905
12
                   << " to NULL_MAP_ONLY reading mode, item column set to SKIP_READING";
1906
12
        return Status::OK();
1907
12
    }
1908
1909
47.2k
    const auto no_sub_column_to_skip = sub_all_access_paths.empty();
1910
47.2k
    const auto no_predicate_sub_column = sub_predicate_access_paths.empty();
1911
1912
47.2k
    if (!no_sub_column_to_skip) {
1913
3.63k
        for (auto& path : sub_all_access_paths) {
1914
3.63k
            if (path.data_access_path.path[0] == ACCESS_ALL) {
1915
3.61k
                path.data_access_path.path[0] = _item_iterator->column_name();
1916
3.61k
            }
1917
3.63k
        }
1918
3.62k
    }
1919
1920
47.2k
    if (!no_predicate_sub_column) {
1921
202
        for (auto& path : sub_predicate_access_paths) {
1922
202
            if (path.data_access_path.path[0] == ACCESS_ALL) {
1923
202
                path.data_access_path.path[0] = _item_iterator->column_name();
1924
202
            }
1925
202
        }
1926
202
    }
1927
1928
47.2k
    if (!no_sub_column_to_skip || !no_predicate_sub_column) {
1929
3.62k
        _item_iterator->set_reading_flag(ReadingFlag::NEED_TO_READ);
1930
3.62k
        RETURN_IF_ERROR(
1931
3.62k
                _item_iterator->set_access_paths(sub_all_access_paths, sub_predicate_access_paths));
1932
3.62k
    }
1933
47.2k
    return Status::OK();
1934
47.2k
}
1935
1936
////////////////////////////////////////////////////////////////////////////////
1937
// StringFileColumnIterator implementation
1938
////////////////////////////////////////////////////////////////////////////////
1939
1940
StringFileColumnIterator::StringFileColumnIterator(std::shared_ptr<ColumnReader> reader)
1941
16.2M
        : FileColumnIterator(std::move(reader)) {}
1942
1943
16.2M
Status StringFileColumnIterator::init(const ColumnIteratorOptions& opts) {
1944
16.2M
    if (read_offset_only()) {
1945
        // Propagate only_read_offsets to the FileColumnIterator's options
1946
151
        auto modified_opts = opts;
1947
151
        modified_opts.only_read_offsets = true;
1948
151
        return FileColumnIterator::init(modified_opts);
1949
151
    }
1950
16.2M
    return FileColumnIterator::init(opts);
1951
16.2M
}
1952
1953
Status StringFileColumnIterator::set_access_paths(
1954
        const TColumnAccessPaths& all_access_paths,
1955
4.80k
        const TColumnAccessPaths& predicate_access_paths) {
1956
4.80k
    if (all_access_paths.empty()) {
1957
3.74k
        return Status::OK();
1958
3.74k
    }
1959
1960
1.06k
    if (!predicate_access_paths.empty()) {
1961
217
        set_reading_flag(ReadingFlag::READING_FOR_PREDICATE);
1962
217
    }
1963
1964
    // Strip the column name from path[0] before checking for meta-only modes.
1965
    // Raw paths look like ["col_name", "OFFSET"] or ["col_name", "NULL"].
1966
1.06k
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
1967
1.06k
    _check_and_set_meta_read_mode(sub_all_access_paths);
1968
    // OFFSET_ONLY mode is fundamentally incompatible with CHAR columns:
1969
    // CHAR is stored padded to its declared length (see
1970
    // OlapColumnDataConvertorChar::clone_and_padding), so the per-row length
1971
    // recorded in dict word info / page headers is always the padded length
1972
    // (e.g. 25 for CHAR(25)) — never the logical length expected by length().
1973
    // Recovering the logical length requires scanning the chars buffer with
1974
    // strnlen() (shrink_padding_chars), which OFFSET_ONLY by definition skips.
1975
    // There is no partial-benefit path: any optimization that still produces
1976
    // the correct length() result must read the chars buffer in full.
1977
    //
1978
    // FE (NestedColumnPruning) already filters CHAR slots out of the
1979
    // OFFSET-only access plan, so reaching this branch means an FE/BE
1980
    // contract violation. Fail loudly instead of silently falling back.
1981
1.06k
    if (read_offset_only() && get_reader() != nullptr &&
1982
1.06k
        get_reader()->get_meta_type() == FieldType::OLAP_FIELD_TYPE_CHAR) {
1983
0
        return Status::InternalError(
1984
0
                "OFFSET_ONLY access path is not supported on CHAR column '{}': CHAR is stored "
1985
0
                "padded so the per-row length information available without reading the chars "
1986
0
                "buffer is always the padded length, not the logical length. The FE planner "
1987
0
                "must not emit an OFFSET access path for CHAR columns.",
1988
0
                _column_name);
1989
0
    }
1990
1.06k
    if (read_offset_only()) {
1991
152
        DLOG(INFO) << "String column iterator set column " << _column_name
1992
152
                   << " to OFFSET_ONLY reading mode";
1993
910
    } else if (read_null_map_only()) {
1994
238
        DLOG(INFO) << "String column iterator set column " << _column_name
1995
238
                   << " to NULL_MAP_ONLY reading mode";
1996
238
    }
1997
1998
1.06k
    return Status::OK();
1999
1.06k
}
2000
2001
////////////////////////////////////////////////////////////////////////////////
2002
2003
27.0M
FileColumnIterator::FileColumnIterator(std::shared_ptr<ColumnReader> reader) : _reader(reader) {}
2004
2005
55.6k
void ColumnIterator::_check_and_set_meta_read_mode(const TColumnAccessPaths& sub_all_access_paths) {
2006
55.6k
    for (const auto& path : sub_all_access_paths) {
2007
6.68k
        if (!path.data_access_path.path.empty()) {
2008
6.68k
            if (StringCaseEqual()(path.data_access_path.path[0], ACCESS_OFFSET)) {
2009
1.80k
                _read_mode = ReadMode::OFFSET_ONLY;
2010
1.80k
                return;
2011
4.87k
            } else if (StringCaseEqual()(path.data_access_path.path[0], ACCESS_NULL)) {
2012
263
                _read_mode = ReadMode::NULL_MAP_ONLY;
2013
263
                return;
2014
263
            }
2015
6.68k
        }
2016
6.66k
    }
2017
53.5k
    _read_mode = ReadMode::DEFAULT;
2018
53.5k
}
2019
2020
26.9M
Status FileColumnIterator::init(const ColumnIteratorOptions& opts) {
2021
26.9M
    if (_reading_flag == ReadingFlag::SKIP_READING) {
2022
2.39k
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
2023
2.39k
        return Status::OK();
2024
2.39k
    }
2025
2026
26.9M
    _opts = opts;
2027
27.0M
    if (!_opts.use_page_cache) {
2028
27.0M
        _reader->disable_index_meta_cache();
2029
27.0M
    }
2030
26.9M
    RETURN_IF_ERROR(get_block_compression_codec(_reader->get_compression(), &_compress_codec));
2031
26.9M
    if (config::enable_low_cardinality_optimize &&
2032
26.9M
        opts.io_ctx.reader_type == ReaderType::READER_QUERY &&
2033
26.9M
        _reader->encoding_info()->encoding() == DICT_ENCODING) {
2034
16.1M
        auto dict_encoding_type = _reader->get_dict_encoding_type();
2035
        // Only if the column is a predicate column, then we need check the all dict encoding flag
2036
        // because we could rewrite the predciate to accelarate query speed. But if it is not a
2037
        // predicate column, then it is useless. And it has a bad impact on cold read(first time read)
2038
        // because it will load the column's ordinal index and zonemap index and maybe other indices.
2039
        // it has bad impact on primary key query. For example, select * from table where pk = 1, and
2040
        // the table has 2000 columns.
2041
16.1M
        if (dict_encoding_type == ColumnReader::UNKNOWN_DICT_ENCODING && opts.is_predicate_column) {
2042
14.0k
            RETURN_IF_ERROR(seek_to_ordinal(_reader->num_rows() - 1));
2043
14.0k
            _is_all_dict_encoding = _page.is_dict_encoding;
2044
14.0k
            _reader->set_dict_encoding_type(_is_all_dict_encoding
2045
14.0k
                                                    ? ColumnReader::ALL_DICT_ENCODING
2046
14.0k
                                                    : ColumnReader::PARTIAL_DICT_ENCODING);
2047
16.1M
        } else {
2048
16.1M
            _is_all_dict_encoding = dict_encoding_type == ColumnReader::ALL_DICT_ENCODING;
2049
16.1M
        }
2050
16.1M
    }
2051
26.9M
    return Status::OK();
2052
26.9M
}
2053
2054
27.0M
FileColumnIterator::~FileColumnIterator() = default;
2055
2056
1.09M
void FileColumnIterator::_trigger_prefetch_if_eligible(ordinal_t ord) {
2057
1.09M
    std::vector<BlockRange> ranges;
2058
1.09M
    if (_prefetcher->need_prefetch(cast_set<uint32_t>(ord), &ranges)) {
2059
842k
        for (const auto& range : ranges) {
2060
842k
            _cached_remote_file_reader->prefetch_range(range.offset, range.size, &_opts.io_ctx);
2061
842k
        }
2062
841k
    }
2063
1.09M
}
2064
2065
4.11M
Status FileColumnIterator::seek_to_ordinal(ordinal_t ord) {
2066
4.11M
    if (_reading_flag == ReadingFlag::SKIP_READING) {
2067
449
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
2068
449
        return Status::OK();
2069
449
    }
2070
2071
18.4E
    LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
2072
18.4E
            "[verbose] FileColumnIterator::seek_to_ordinal seek to ordinal {}, enable_prefetch={}",
2073
18.4E
            ord, _enable_prefetch);
2074
4.11M
    if (_enable_prefetch) {
2075
1.09M
        _trigger_prefetch_if_eligible(ord);
2076
1.09M
    }
2077
2078
    // if current page contains this row, we don't need to seek
2079
4.11M
    if (!_page || !_page.contains(ord) || !_page_iter.valid()) {
2080
1.51M
        RETURN_IF_ERROR(_reader->seek_at_or_before(ord, &_page_iter, _opts));
2081
1.51M
        RETURN_IF_ERROR(_read_data_page(_page_iter));
2082
1.51M
    }
2083
4.11M
    RETURN_IF_ERROR(_seek_to_pos_in_page(&_page, ord - _page.first_ordinal));
2084
4.11M
    _current_ordinal = ord;
2085
4.11M
    return Status::OK();
2086
4.11M
}
2087
2088
0
Status FileColumnIterator::seek_to_page_start() {
2089
0
    return seek_to_ordinal(_page.first_ordinal);
2090
0
}
2091
2092
4.16M
Status FileColumnIterator::_seek_to_pos_in_page(ParsedPage* page, ordinal_t offset_in_page) const {
2093
4.16M
    if (page->offset_in_page == offset_in_page) {
2094
        // fast path, do nothing
2095
1.81M
        return Status::OK();
2096
1.81M
    }
2097
2098
2.35M
    ordinal_t pos_in_data = offset_in_page;
2099
2.35M
    if (_page.has_null) {
2100
132k
        ordinal_t offset_in_data = 0;
2101
132k
        ordinal_t skips = offset_in_page;
2102
2103
132k
        if (offset_in_page > page->offset_in_page) {
2104
            // forward, reuse null bitmap
2105
89.7k
            skips = offset_in_page - page->offset_in_page;
2106
89.7k
            offset_in_data = page->data_decoder->current_index();
2107
89.7k
        } else {
2108
            // rewind null bitmap, and
2109
43.0k
            page->null_decoder = RleDecoder<bool>((const uint8_t*)page->null_bitmap.data,
2110
43.0k
                                                  cast_set<int>(page->null_bitmap.size), 1);
2111
43.0k
        }
2112
2113
132k
        auto skip_nulls = page->null_decoder.Skip(skips);
2114
132k
        pos_in_data = offset_in_data + skips - skip_nulls;
2115
132k
    }
2116
2117
2.35M
    RETURN_IF_ERROR(page->data_decoder->seek_to_position_in_page(pos_in_data));
2118
2.35M
    page->offset_in_page = offset_in_page;
2119
2.35M
    return Status::OK();
2120
2.35M
}
2121
2122
10.8k
Status FileColumnIterator::next_batch_of_zone_map(size_t* n, MutableColumnPtr& dst) {
2123
10.8k
    return _reader->next_batch_of_zone_map(n, dst);
2124
10.8k
}
2125
2126
3.30M
Status FileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
2127
3.30M
    if (read_null_map_only()) {
2128
2.99k
        DLOG(INFO) << "File column iterator column " << _column_name
2129
2.99k
                   << " in NULL_MAP_ONLY mode, reading only null map.";
2130
2.99k
        DORIS_CHECK(dst->is_nullable());
2131
2.99k
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
2132
2.99k
        auto& null_map_data = nullable_col.get_null_map_data();
2133
2134
2.99k
        size_t remaining = *n;
2135
2.99k
        *has_null = false;
2136
6.05k
        while (remaining > 0) {
2137
3.05k
            if (!_page.has_remaining()) {
2138
51
                bool eos = false;
2139
51
                RETURN_IF_ERROR(_load_next_page(&eos));
2140
51
                if (eos) {
2141
0
                    break;
2142
0
                }
2143
51
            }
2144
2145
3.05k
            size_t nrows_in_page = std::min(remaining, _page.remaining());
2146
3.05k
            size_t nrows_to_read = nrows_in_page;
2147
3.05k
            if (_page.has_null) {
2148
193k
                while (nrows_to_read > 0) {
2149
190k
                    bool is_null = false;
2150
190k
                    size_t this_run = _page.null_decoder.GetNextRun(&is_null, nrows_to_read);
2151
190k
                    const size_t cur_size = null_map_data.size();
2152
190k
                    null_map_data.resize(cur_size + this_run);
2153
190k
                    memset(null_map_data.data() + cur_size, is_null ? 1 : 0, this_run);
2154
190k
                    if (is_null) {
2155
101k
                        *has_null = true;
2156
101k
                    }
2157
190k
                    nrows_to_read -= this_run;
2158
190k
                    _page.offset_in_page += this_run;
2159
190k
                    _current_ordinal += this_run;
2160
190k
                }
2161
2.96k
            } else {
2162
93
                const size_t cur_size = null_map_data.size();
2163
93
                null_map_data.resize(cur_size + nrows_to_read);
2164
93
                memset(null_map_data.data() + cur_size, 0, nrows_to_read);
2165
93
                _page.offset_in_page += nrows_to_read;
2166
93
                _current_ordinal += nrows_to_read;
2167
93
            }
2168
3.05k
            remaining -= nrows_in_page;
2169
3.05k
        }
2170
2.99k
        *n -= remaining;
2171
2.99k
        nullable_col.get_nested_column().insert_many_defaults(*n);
2172
2.99k
        return Status::OK();
2173
2.99k
    }
2174
2175
3.30M
    if (_reading_flag == ReadingFlag::SKIP_READING) {
2176
449
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
2177
449
        dst->insert_many_defaults(*n);
2178
449
        return Status::OK();
2179
449
    }
2180
2181
3.29M
    size_t curr_size = dst->byte_size();
2182
3.29M
    dst->reserve(*n);
2183
3.29M
    size_t remaining = *n;
2184
3.29M
    *has_null = false;
2185
6.66M
    while (remaining > 0) {
2186
3.35M
        if (!_page.has_remaining()) {
2187
58.4k
            bool eos = false;
2188
58.4k
            RETURN_IF_ERROR(_load_next_page(&eos));
2189
58.4k
            if (eos) {
2190
0
                break;
2191
0
            }
2192
58.4k
        }
2193
2194
        // number of rows to be read from this page
2195
3.35M
        size_t nrows_in_page = std::min(remaining, _page.remaining());
2196
3.35M
        size_t nrows_to_read = nrows_in_page;
2197
3.35M
        if (_page.has_null) {
2198
2.47M
            while (nrows_to_read > 0) {
2199
2.25M
                bool is_null = false;
2200
2.25M
                size_t this_run = _page.null_decoder.GetNextRun(&is_null, nrows_to_read);
2201
                // we use num_rows only for CHECK
2202
2.25M
                size_t num_rows = this_run;
2203
2.25M
                if (!is_null) {
2204
1.15M
                    RETURN_IF_ERROR(_page.data_decoder->next_batch(&num_rows, dst));
2205
1.15M
                    DCHECK_EQ(this_run, num_rows);
2206
1.15M
                } else {
2207
1.10M
                    *has_null = true;
2208
1.10M
                    auto* null_col = check_and_get_column<ColumnNullable>(dst.get());
2209
1.10M
                    if (null_col != nullptr) {
2210
1.10M
                        null_col->insert_many_defaults(this_run);
2211
18.4E
                    } else {
2212
18.4E
                        return Status::InternalError("unexpected column type in column reader");
2213
18.4E
                    }
2214
1.10M
                }
2215
2216
2.25M
                nrows_to_read -= this_run;
2217
2.25M
                _page.offset_in_page += this_run;
2218
2.25M
                _current_ordinal += this_run;
2219
2.25M
            }
2220
3.14M
        } else {
2221
3.14M
            RETURN_IF_ERROR(_page.data_decoder->next_batch(&nrows_to_read, dst));
2222
3.14M
            DCHECK_EQ(nrows_to_read, nrows_in_page);
2223
2224
3.14M
            _page.offset_in_page += nrows_to_read;
2225
3.14M
            _current_ordinal += nrows_to_read;
2226
3.14M
        }
2227
3.36M
        remaining -= nrows_in_page;
2228
3.36M
    }
2229
3.30M
    *n -= remaining;
2230
3.30M
    _opts.stats->bytes_read += (dst->byte_size() - curr_size) + BitmapSize(*n);
2231
2232
#ifdef BE_TEST
2233
    _reader->check_data_by_zone_map_for_test(dst);
2234
#endif
2235
3.30M
    return Status::OK();
2236
3.29M
}
2237
2238
Status FileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
2239
744k
                                          MutableColumnPtr& dst) {
2240
744k
    if (read_null_map_only()) {
2241
16
        DLOG(INFO) << "File column iterator column " << _column_name
2242
16
                   << " in NULL_MAP_ONLY mode, reading only null map by rowids.";
2243
2244
16
        DORIS_CHECK(dst->is_nullable());
2245
16
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
2246
16
        auto& null_map_data = nullable_col.get_null_map_data();
2247
16
        const size_t base_size = null_map_data.size();
2248
16
        null_map_data.resize(base_size + count);
2249
2250
16
        size_t remaining = count;
2251
16
        size_t total_read_count = 0;
2252
16
        size_t nrows_to_read = 0;
2253
32
        while (remaining > 0) {
2254
16
            RETURN_IF_ERROR(seek_to_ordinal(rowids[total_read_count]));
2255
2256
16
            nrows_to_read = std::min(remaining, _page.remaining());
2257
2258
16
            if (_page.has_null) {
2259
2
                size_t already_read = 0;
2260
4
                while ((nrows_to_read - already_read) > 0) {
2261
2
                    bool is_null = false;
2262
2
                    size_t this_run = std::min(nrows_to_read - already_read, _page.remaining());
2263
2
                    if (UNLIKELY(this_run == 0)) {
2264
0
                        break;
2265
0
                    }
2266
2
                    this_run = _page.null_decoder.GetNextRun(&is_null, this_run);
2267
2268
2
                    size_t offset = total_read_count + already_read;
2269
2
                    size_t this_read_count = 0;
2270
2
                    rowid_t current_ordinal_in_page =
2271
2
                            cast_set<uint32_t>(_page.offset_in_page + _page.first_ordinal);
2272
4
                    for (size_t i = 0; i < this_run; ++i) {
2273
2
                        if (rowids[offset + i] - current_ordinal_in_page >= this_run) {
2274
0
                            break;
2275
0
                        }
2276
2
                        this_read_count++;
2277
2
                    }
2278
2279
2
                    if (this_read_count > 0) {
2280
2
                        memset(null_map_data.data() + base_size + offset, is_null ? 1 : 0,
2281
2
                               this_read_count);
2282
2
                    }
2283
2284
2
                    already_read += this_read_count;
2285
2
                    _page.offset_in_page += this_run;
2286
2
                }
2287
2288
2
                nrows_to_read = already_read;
2289
2
                total_read_count += nrows_to_read;
2290
2
                remaining -= nrows_to_read;
2291
14
            } else {
2292
14
                memset(null_map_data.data() + base_size + total_read_count, 0, nrows_to_read);
2293
14
                total_read_count += nrows_to_read;
2294
14
                remaining -= nrows_to_read;
2295
14
            }
2296
16
        }
2297
2298
16
        null_map_data.resize(base_size + total_read_count);
2299
16
        nullable_col.get_nested_column().insert_many_defaults(total_read_count);
2300
16
        return Status::OK();
2301
16
    }
2302
2303
744k
    if (_reading_flag == ReadingFlag::SKIP_READING) {
2304
0
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
2305
0
        dst->insert_many_defaults(count);
2306
0
        return Status::OK();
2307
0
    }
2308
2309
744k
    size_t remaining = count;
2310
744k
    size_t total_read_count = 0;
2311
744k
    size_t nrows_to_read = 0;
2312
1.51M
    while (remaining > 0) {
2313
774k
        RETURN_IF_ERROR(seek_to_ordinal(rowids[total_read_count]));
2314
2315
        // number of rows to be read from this page
2316
774k
        nrows_to_read = std::min(remaining, _page.remaining());
2317
2318
774k
        if (_page.has_null) {
2319
70.2k
            size_t already_read = 0;
2320
4.74M
            while ((nrows_to_read - already_read) > 0) {
2321
4.67M
                bool is_null = false;
2322
4.67M
                size_t this_run = std::min(nrows_to_read - already_read, _page.remaining());
2323
4.67M
                if (UNLIKELY(this_run == 0)) {
2324
177
                    break;
2325
177
                }
2326
4.67M
                this_run = _page.null_decoder.GetNextRun(&is_null, this_run);
2327
4.67M
                size_t offset = total_read_count + already_read;
2328
4.67M
                size_t this_read_count = 0;
2329
4.67M
                rowid_t current_ordinal_in_page =
2330
4.67M
                        cast_set<uint32_t>(_page.offset_in_page + _page.first_ordinal);
2331
21.2M
                for (size_t i = 0; i < this_run; ++i) {
2332
19.9M
                    if (rowids[offset + i] - current_ordinal_in_page >= this_run) {
2333
3.43M
                        break;
2334
3.43M
                    }
2335
16.5M
                    this_read_count++;
2336
16.5M
                }
2337
2338
4.67M
                auto origin_index = _page.data_decoder->current_index();
2339
4.67M
                if (this_read_count > 0) {
2340
1.30M
                    if (is_null) {
2341
712k
                        auto* null_col = check_and_get_column<ColumnNullable>(dst.get());
2342
712k
                        if (UNLIKELY(null_col == nullptr)) {
2343
0
                            return Status::InternalError("unexpected column type in column reader");
2344
0
                        }
2345
2346
712k
                        null_col->insert_many_defaults(this_read_count);
2347
712k
                    } else {
2348
595k
                        size_t read_count = this_read_count;
2349
2350
                        // ordinal in nullable columns' data buffer maybe be not continuously(the data doesn't contain null value),
2351
                        // so we need use `page_start_off_in_decoder` to calculate the actual offset in `data_decoder`
2352
595k
                        size_t page_start_off_in_decoder =
2353
595k
                                _page.first_ordinal + _page.offset_in_page - origin_index;
2354
595k
                        RETURN_IF_ERROR(_page.data_decoder->read_by_rowids(
2355
595k
                                &rowids[offset], page_start_off_in_decoder, &read_count, dst));
2356
595k
                        DCHECK_EQ(read_count, this_read_count);
2357
595k
                    }
2358
1.30M
                }
2359
2360
4.67M
                if (!is_null) {
2361
3.70M
                    RETURN_IF_ERROR(
2362
3.70M
                            _page.data_decoder->seek_to_position_in_page(origin_index + this_run));
2363
3.70M
                }
2364
2365
4.67M
                already_read += this_read_count;
2366
4.67M
                _page.offset_in_page += this_run;
2367
4.67M
                DCHECK(_page.offset_in_page <= _page.num_rows);
2368
4.67M
            }
2369
2370
70.2k
            nrows_to_read = already_read;
2371
70.2k
            total_read_count += nrows_to_read;
2372
70.2k
            remaining -= nrows_to_read;
2373
704k
        } else {
2374
704k
            RETURN_IF_ERROR(_page.data_decoder->read_by_rowids(
2375
704k
                    &rowids[total_read_count], _page.first_ordinal, &nrows_to_read, dst));
2376
704k
            total_read_count += nrows_to_read;
2377
704k
            remaining -= nrows_to_read;
2378
704k
        }
2379
774k
    }
2380
744k
    return Status::OK();
2381
744k
}
2382
2383
58.4k
Status FileColumnIterator::_load_next_page(bool* eos) {
2384
58.4k
    _page_iter.next();
2385
58.4k
    if (!_page_iter.valid()) {
2386
0
        *eos = true;
2387
0
        return Status::OK();
2388
0
    }
2389
2390
58.4k
    RETURN_IF_ERROR(_read_data_page(_page_iter));
2391
58.4k
    RETURN_IF_ERROR(_seek_to_pos_in_page(&_page, 0));
2392
58.4k
    *eos = false;
2393
58.4k
    return Status::OK();
2394
58.4k
}
2395
2396
1.57M
Status FileColumnIterator::_read_data_page(const OrdinalPageIndexIterator& iter) {
2397
1.57M
    PageHandle handle;
2398
1.57M
    Slice page_body;
2399
1.57M
    PageFooterPB footer;
2400
1.57M
    _opts.type = DATA_PAGE;
2401
1.57M
    PageDecoderOptions decoder_opts;
2402
1.57M
    decoder_opts.only_read_offsets = _opts.only_read_offsets;
2403
1.57M
    RETURN_IF_ERROR(
2404
1.57M
            _reader->read_page(_opts, iter.page(), &handle, &page_body, &footer, _compress_codec));
2405
    // parse data page
2406
1.57M
    auto st = ParsedPage::create(std::move(handle), page_body, footer.data_page_footer(),
2407
1.57M
                                 _reader->encoding_info(), iter.page(), iter.page_index(), &_page,
2408
1.57M
                                 decoder_opts);
2409
1.57M
    if (!st.ok()) {
2410
0
        LOG(WARNING) << "failed to create ParsedPage, file=" << _opts.file_reader->path().native()
2411
0
                     << ", page_offset=" << iter.page().offset << ", page_size=" << iter.page().size
2412
0
                     << ", page_index=" << iter.page_index() << ", error=" << st;
2413
0
        return st;
2414
0
    }
2415
2416
    // dictionary page is read when the first data page that uses it is read,
2417
    // this is to optimize the memory usage: when there is no query on one column, we could
2418
    // release the memory of dictionary page.
2419
    // note that concurrent iterators for the same column won't repeatedly read dictionary page
2420
    // because of page cache.
2421
1.57M
    if (_reader->encoding_info()->encoding() == DICT_ENCODING) {
2422
439k
        auto dict_page_decoder = reinterpret_cast<BinaryDictPageDecoder*>(_page.data_decoder.get());
2423
439k
        if (dict_page_decoder->is_dict_encoding()) {
2424
414k
            if (_dict_decoder == nullptr) {
2425
401k
                RETURN_IF_ERROR(_read_dict_data());
2426
401k
                CHECK_NOTNULL(_dict_decoder);
2427
401k
            }
2428
2429
414k
            dict_page_decoder->set_dict_decoder(cast_set<uint32_t>(_dict_decoder->count()),
2430
414k
                                                _dict_word_info.get());
2431
414k
        }
2432
439k
    }
2433
1.57M
    return Status::OK();
2434
1.57M
}
2435
2436
401k
Status FileColumnIterator::_read_dict_data() {
2437
401k
    CHECK_EQ(_reader->encoding_info()->encoding(), DICT_ENCODING);
2438
    // read dictionary page
2439
401k
    Slice dict_data;
2440
401k
    PageFooterPB dict_footer;
2441
401k
    _opts.type = INDEX_PAGE;
2442
2443
401k
    RETURN_IF_ERROR(_reader->read_page(_opts, _reader->get_dict_page_pointer(), &_dict_page_handle,
2444
401k
                                       &dict_data, &dict_footer, _compress_codec, true));
2445
401k
    const EncodingInfo* encoding_info;
2446
401k
    RETURN_IF_ERROR(EncodingInfo::get(FieldType::OLAP_FIELD_TYPE_VARCHAR,
2447
401k
                                      dict_footer.dict_page_footer().encoding(), {},
2448
401k
                                      &encoding_info));
2449
401k
    RETURN_IF_ERROR(encoding_info->create_page_decoder(dict_data, {}, _dict_decoder));
2450
401k
    RETURN_IF_ERROR(_dict_decoder->init());
2451
2452
401k
    _dict_word_info.reset(new StringRef[_dict_decoder->count()]);
2453
401k
    RETURN_IF_ERROR(_dict_decoder->get_dict_word_info(_dict_word_info.get()));
2454
401k
    return Status::OK();
2455
401k
}
2456
2457
Status FileColumnIterator::get_row_ranges_by_zone_map(
2458
        const AndBlockColumnPredicate* col_predicates,
2459
        const std::vector<std::shared_ptr<const ColumnPredicate>>* delete_predicates,
2460
107k
        RowRanges* row_ranges) {
2461
107k
    if (_reader->has_zone_map()) {
2462
107k
        RETURN_IF_ERROR(_reader->get_row_ranges_by_zone_map(col_predicates, delete_predicates,
2463
107k
                                                            row_ranges, _opts));
2464
107k
    }
2465
107k
    return Status::OK();
2466
107k
}
2467
2468
Status FileColumnIterator::get_row_ranges_by_bloom_filter(
2469
108k
        const AndBlockColumnPredicate* col_predicates, RowRanges* row_ranges) {
2470
108k
    if ((col_predicates->can_do_bloom_filter(false) && _reader->has_bloom_filter_index(false)) ||
2471
108k
        (col_predicates->can_do_bloom_filter(true) && _reader->has_bloom_filter_index(true))) {
2472
100
        RETURN_IF_ERROR(_reader->get_row_ranges_by_bloom_filter(col_predicates, row_ranges, _opts));
2473
100
    }
2474
108k
    return Status::OK();
2475
108k
}
2476
2477
Status FileColumnIterator::get_row_ranges_by_dict(const AndBlockColumnPredicate* col_predicates,
2478
110k
                                                  RowRanges* row_ranges) {
2479
110k
    if (!_is_all_dict_encoding) {
2480
100k
        return Status::OK();
2481
100k
    }
2482
2483
9.89k
    if (!_dict_decoder) {
2484
24
        RETURN_IF_ERROR(_read_dict_data());
2485
24
        CHECK_NOTNULL(_dict_decoder);
2486
24
    }
2487
2488
9.89k
    if (!col_predicates->evaluate_and(_dict_word_info.get(), _dict_decoder->count())) {
2489
1.12k
        row_ranges->clear();
2490
1.12k
    }
2491
9.89k
    return Status::OK();
2492
9.89k
}
2493
2494
880k
Status FileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
2495
880k
    if (_cached_remote_file_reader =
2496
880k
                std::dynamic_pointer_cast<io::CachedRemoteFileReader>(_reader->_file_reader);
2497
880k
        !_cached_remote_file_reader) {
2498
0
        return Status::OK();
2499
0
    }
2500
880k
    _enable_prefetch = true;
2501
880k
    _prefetcher = std::make_unique<SegmentPrefetcher>(params.config);
2502
880k
    RETURN_IF_ERROR(_prefetcher->init(_reader, params.read_options));
2503
880k
    return Status::OK();
2504
880k
}
2505
2506
void FileColumnIterator::collect_prefetchers(
2507
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
2508
878k
        PrefetcherInitMethod init_method) {
2509
879k
    if (_prefetcher) {
2510
879k
        prefetchers[init_method].emplace_back(_prefetcher.get());
2511
879k
    }
2512
878k
}
2513
2514
21.4k
Status DefaultValueColumnIterator::init(const ColumnIteratorOptions& opts) {
2515
21.4k
    _opts = opts;
2516
    // be consistent with segment v1
2517
    // if _has_default_value, we should create default column iterator for this column, and
2518
    // "NULL" is a special default value which means the default value is null.
2519
21.4k
    if (_has_default_value) {
2520
1.46k
        if (_default_value == "NULL") {
2521
703
            _default_value_field = Field::create_field<TYPE_NULL>(Null {});
2522
766
        } else {
2523
766
            if (_type == FieldType::OLAP_FIELD_TYPE_ARRAY) {
2524
8
                if (_default_value != "[]") {
2525
0
                    return Status::NotSupported("Array default {} is unsupported", _default_value);
2526
8
                } else {
2527
8
                    _default_value_field = Field::create_field<TYPE_ARRAY>(Array {});
2528
8
                    return Status::OK();
2529
8
                }
2530
758
            } else if (_type == FieldType::OLAP_FIELD_TYPE_STRUCT) {
2531
0
                return Status::NotSupported("STRUCT default type is unsupported");
2532
758
            } else if (_type == FieldType::OLAP_FIELD_TYPE_MAP) {
2533
0
                return Status::NotSupported("MAP default type is unsupported");
2534
0
            }
2535
758
            const auto t = _type;
2536
758
            const auto serde = DataTypeFactory::instance()
2537
758
                                       .create_data_type(t, _precision, _scale, _len)
2538
758
                                       ->get_serde();
2539
758
            RETURN_IF_ERROR(serde->from_fe_string(_default_value, _default_value_field));
2540
758
        }
2541
20.0k
    } else if (_is_nullable) {
2542
20.0k
        _default_value_field = Field::create_field<TYPE_NULL>(Null {});
2543
18.4E
    } else {
2544
18.4E
        return Status::InternalError(
2545
18.4E
                "invalid default value column for no default value and not nullable");
2546
18.4E
    }
2547
21.4k
    return Status::OK();
2548
21.4k
}
2549
2550
2.50k
Status DefaultValueColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
2551
2.50k
    *has_null = _default_value_field.is_null();
2552
2.50k
    _insert_many_default(dst, *n);
2553
2.50k
    return Status::OK();
2554
2.50k
}
2555
2556
Status DefaultValueColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
2557
5.78k
                                                  MutableColumnPtr& dst) {
2558
5.78k
    _insert_many_default(dst, count);
2559
5.78k
    return Status::OK();
2560
5.78k
}
2561
2562
8.28k
void DefaultValueColumnIterator::_insert_many_default(MutableColumnPtr& dst, size_t n) {
2563
8.28k
    if (_default_value_field.is_null()) {
2564
7.86k
        dst->insert_many_defaults(n);
2565
7.86k
    } else {
2566
419
        dst = dst->convert_to_predicate_column_if_dictionary();
2567
419
        dst->insert_duplicate_fields(_default_value_field, n);
2568
419
    }
2569
8.28k
}
2570
2571
3.18k
Status RowIdColumnIteratorV2::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
2572
3.18k
    auto* string_column = assert_cast<ColumnString*, TypeCheckOnRelease::DISABLE>(dst.get());
2573
2574
10.8M
    for (uint32_t i = 0; i < *n; ++i) {
2575
10.8M
        uint32_t row_id = _current_rowid + i;
2576
10.8M
        GlobalRowLoacationV2 location(_version, _backend_id, _file_id, row_id);
2577
10.8M
        string_column->insert_data(reinterpret_cast<const char*>(&location),
2578
10.8M
                                   sizeof(GlobalRowLoacationV2));
2579
10.8M
    }
2580
3.18k
    _current_rowid += *n;
2581
3.18k
    return Status::OK();
2582
3.18k
}
2583
2584
Status RowIdColumnIteratorV2::read_by_rowids(const rowid_t* rowids, const size_t count,
2585
44.0k
                                             MutableColumnPtr& dst) {
2586
44.0k
    auto* string_column = assert_cast<ColumnString*>(dst.get());
2587
2588
31.1M
    for (size_t i = 0; i < count; ++i) {
2589
31.1M
        uint32_t row_id = rowids[i];
2590
31.1M
        GlobalRowLoacationV2 location(_version, _backend_id, _file_id, row_id);
2591
31.1M
        string_column->insert_data(reinterpret_cast<const char*>(&location),
2592
31.1M
                                   sizeof(GlobalRowLoacationV2));
2593
31.1M
    }
2594
44.0k
    return Status::OK();
2595
44.0k
}
2596
2597
} // namespace doris::segment_v2