Coverage Report

Created: 2026-03-16 12:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format/table/iceberg_reader.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "format/table/iceberg_reader.h"
19
20
#include <gen_cpp/Descriptors_types.h>
21
#include <gen_cpp/Metrics_types.h>
22
#include <gen_cpp/PlanNodes_types.h>
23
#include <gen_cpp/parquet_types.h>
24
#include <glog/logging.h>
25
#include <parallel_hashmap/phmap.h>
26
#include <rapidjson/document.h>
27
28
#include <algorithm>
29
#include <cstring>
30
#include <functional>
31
#include <memory>
32
#include <set>
33
34
#include "common/compiler_util.h" // IWYU pragma: keep
35
#include "common/status.h"
36
#include "core/assert_cast.h"
37
#include "core/block/block.h"
38
#include "core/block/column_with_type_and_name.h"
39
#include "core/column/column.h"
40
#include "core/column/column_string.h"
41
#include "core/column/column_vector.h"
42
#include "core/data_type/data_type_factory.hpp"
43
#include "core/data_type/define_primitive_type.h"
44
#include "core/data_type/primitive_type.h"
45
#include "core/string_ref.h"
46
#include "exprs/aggregate/aggregate_function.h"
47
#include "format/format_common.h"
48
#include "format/generic_reader.h"
49
#include "format/orc/vorc_reader.h"
50
#include "format/parquet/schema_desc.h"
51
#include "format/parquet/vparquet_column_chunk_reader.h"
52
#include "format/table/deletion_vector_reader.h"
53
#include "format/table/iceberg/iceberg_orc_nested_column_utils.h"
54
#include "format/table/iceberg/iceberg_parquet_nested_column_utils.h"
55
#include "format/table/nested_column_access_helper.h"
56
#include "format/table/table_format_reader.h"
57
#include "runtime/runtime_state.h"
58
#include "util/coding.h"
59
60
namespace cctz {
61
#include "common/compile_check_begin.h"
62
class time_zone;
63
} // namespace cctz
64
namespace doris {
65
class RowDescriptor;
66
class SlotDescriptor;
67
class TupleDescriptor;
68
69
namespace io {
70
struct IOContext;
71
} // namespace io
72
class VExprContext;
73
} // namespace doris
74
75
namespace doris {
76
const std::string IcebergOrcReader::ICEBERG_ORC_ATTRIBUTE = "iceberg.id";
77
78
IcebergTableReader::IcebergTableReader(std::unique_ptr<GenericReader> file_format_reader,
79
                                       RuntimeProfile* profile, RuntimeState* state,
80
                                       const TFileScanRangeParams& params,
81
                                       const TFileRangeDesc& range, ShardedKVCache* kv_cache,
82
                                       io::IOContext* io_ctx, FileMetaCache* meta_cache)
83
23.5k
        : TableFormatReader(std::move(file_format_reader), state, profile, params, range, io_ctx,
84
23.5k
                            meta_cache),
85
23.5k
          _kv_cache(kv_cache) {
86
23.5k
    static const char* iceberg_profile = "IcebergProfile";
87
23.5k
    ADD_TIMER(_profile, iceberg_profile);
88
23.5k
    _iceberg_profile.num_delete_files =
89
23.5k
            ADD_CHILD_COUNTER(_profile, "NumDeleteFiles", TUnit::UNIT, iceberg_profile);
90
23.5k
    _iceberg_profile.num_delete_rows =
91
23.5k
            ADD_CHILD_COUNTER(_profile, "NumDeleteRows", TUnit::UNIT, iceberg_profile);
92
23.5k
    _iceberg_profile.delete_files_read_time =
93
23.5k
            ADD_CHILD_TIMER(_profile, "DeleteFileReadTime", iceberg_profile);
94
23.5k
    _iceberg_profile.delete_rows_sort_time =
95
23.5k
            ADD_CHILD_TIMER(_profile, "DeleteRowsSortTime", iceberg_profile);
96
23.5k
    _iceberg_profile.parse_delete_file_time =
97
23.5k
            ADD_CHILD_TIMER(_profile, "ParseDeleteFileTime", iceberg_profile);
98
23.5k
}
99
100
30.3k
Status IcebergTableReader::get_next_block_inner(Block* block, size_t* read_rows, bool* eof) {
101
30.3k
    RETURN_IF_ERROR(_expand_block_if_need(block));
102
30.3k
    RETURN_IF_ERROR(_file_format_reader->get_next_block(block, read_rows, eof));
103
104
30.3k
    if (_equality_delete_impls.size() > 0) {
105
1.96k
        std::unique_ptr<IColumn::Filter> filter =
106
1.96k
                std::make_unique<IColumn::Filter>(block->rows(), 1);
107
2.48k
        for (auto& equality_delete_impl : _equality_delete_impls) {
108
2.48k
            RETURN_IF_ERROR(equality_delete_impl->filter_data_block(
109
2.48k
                    block, _col_name_to_block_idx, _id_to_block_column_name, *filter));
110
2.48k
        }
111
1.96k
        Block::filter_block_internal(block, *filter, block->columns());
112
1.96k
    }
113
114
30.3k
    *read_rows = block->rows();
115
30.3k
    return _shrink_block_if_need(block);
116
30.3k
}
117
118
23.4k
Status IcebergTableReader::init_row_filters() {
119
    // We get the count value by doris's be, so we don't need to read the delete file
120
23.4k
    if (_push_down_agg_type == TPushAggOp::type::COUNT && _table_level_row_count > 0) {
121
0
        return Status::OK();
122
0
    }
123
124
23.4k
    const auto& table_desc = _range.table_format_params.iceberg_params;
125
23.4k
    const auto& version = table_desc.format_version;
126
23.4k
    if (version < MIN_SUPPORT_DELETE_FILES_VERSION) {
127
1.70k
        return Status::OK();
128
1.70k
    }
129
130
21.7k
    std::vector<TIcebergDeleteFileDesc> position_delete_files;
131
21.7k
    std::vector<TIcebergDeleteFileDesc> equality_delete_files;
132
21.7k
    std::vector<TIcebergDeleteFileDesc> deletion_vector_files;
133
21.7k
    for (const TIcebergDeleteFileDesc& desc : table_desc.delete_files) {
134
10.6k
        if (desc.content == POSITION_DELETE) {
135
5.25k
            position_delete_files.emplace_back(desc);
136
5.40k
        } else if (desc.content == EQUALITY_DELETE) {
137
3.04k
            equality_delete_files.emplace_back(desc);
138
3.04k
        } else if (desc.content == DELETION_VECTOR) {
139
2.36k
            deletion_vector_files.emplace_back(desc);
140
2.36k
        }
141
10.6k
    }
142
143
21.7k
    if (!equality_delete_files.empty()) {
144
1.33k
        RETURN_IF_ERROR(_process_equality_delete(equality_delete_files));
145
1.33k
        _file_format_reader->set_push_down_agg_type(TPushAggOp::NONE);
146
1.33k
    }
147
148
21.7k
    if (!deletion_vector_files.empty()) {
149
2.36k
        if (deletion_vector_files.size() != 1) [[unlikely]] {
150
            /*
151
             * Deletion vectors are a binary representation of deletes for a single data file that is more efficient
152
             * at execution time than position delete files. Unlike equality or position delete files, there can be
153
             * at most one deletion vector for a given data file in a snapshot.
154
             */
155
0
            return Status::DataQualityError("This iceberg data file has multiple DVs.");
156
0
        }
157
2.36k
        RETURN_IF_ERROR(
158
2.36k
                read_deletion_vector(table_desc.original_file_path, deletion_vector_files[0]));
159
160
2.36k
        _file_format_reader->set_push_down_agg_type(TPushAggOp::NONE);
161
        // Readers can safely ignore position delete files if there is a DV for a data file.
162
19.3k
    } else if (!position_delete_files.empty()) {
163
1.65k
        RETURN_IF_ERROR(
164
1.65k
                _position_delete_base(table_desc.original_file_path, position_delete_files));
165
1.65k
        _file_format_reader->set_push_down_agg_type(TPushAggOp::NONE);
166
1.65k
    }
167
168
21.7k
    COUNTER_UPDATE(_iceberg_profile.num_delete_files, table_desc.delete_files.size());
169
21.7k
    return Status::OK();
170
21.7k
}
171
172
void IcebergTableReader::_generate_equality_delete_block(
173
        Block* block, const std::vector<std::string>& equality_delete_col_names,
174
6.27k
        const std::vector<DataTypePtr>& equality_delete_col_types) {
175
16.0k
    for (int i = 0; i < equality_delete_col_names.size(); ++i) {
176
9.76k
        DataTypePtr data_type = make_nullable(equality_delete_col_types[i]);
177
9.76k
        MutableColumnPtr data_column = data_type->create_column();
178
9.76k
        block->insert(ColumnWithTypeAndName(std::move(data_column), data_type,
179
9.76k
                                            equality_delete_col_names[i]));
180
9.76k
    }
181
6.27k
}
182
183
30.3k
Status IcebergTableReader::_expand_block_if_need(Block* block) {
184
30.3k
    std::set<std::string> names;
185
30.3k
    auto block_names = block->get_names();
186
30.3k
    names.insert(block_names.begin(), block_names.end());
187
30.3k
    for (auto& col : _expand_columns) {
188
946
        col.column->assume_mutable()->clear();
189
946
        if (names.contains(col.name)) {
190
0
            return Status::InternalError("Wrong expand column '{}'", col.name);
191
0
        }
192
946
        names.insert(col.name);
193
946
        (*_col_name_to_block_idx)[col.name] = static_cast<uint32_t>(block->columns());
194
946
        block->insert(col);
195
946
    }
196
30.3k
    return Status::OK();
197
30.3k
}
198
199
30.4k
Status IcebergTableReader::_shrink_block_if_need(Block* block) {
200
30.4k
    std::set<size_t> positions_to_erase;
201
30.4k
    for (const std::string& expand_col : _expand_col_names) {
202
946
        if (!_col_name_to_block_idx->contains(expand_col)) {
203
0
            return Status::InternalError("Wrong erase column '{}', block: {}", expand_col,
204
0
                                         block->dump_names());
205
0
        }
206
946
        positions_to_erase.emplace((*_col_name_to_block_idx)[expand_col]);
207
946
    }
208
30.4k
    block->erase(positions_to_erase);
209
30.4k
    for (const std::string& expand_col : _expand_col_names) {
210
946
        _col_name_to_block_idx->erase(expand_col);
211
946
    }
212
30.4k
    return Status::OK();
213
30.4k
}
214
215
Status IcebergTableReader::_position_delete_base(
216
1.64k
        const std::string data_file_path, const std::vector<TIcebergDeleteFileDesc>& delete_files) {
217
1.64k
    std::vector<DeleteRows*> delete_rows_array;
218
1.64k
    int64_t num_delete_rows = 0;
219
5.26k
    for (const auto& delete_file : delete_files) {
220
5.26k
        SCOPED_TIMER(_iceberg_profile.delete_files_read_time);
221
5.26k
        Status create_status = Status::OK();
222
5.26k
        auto* delete_file_cache = _kv_cache->get<DeleteFile>(
223
5.26k
                _delet_file_cache_key(delete_file.path), [&]() -> DeleteFile* {
224
1.38k
                    auto* position_delete = new DeleteFile;
225
1.38k
                    TFileRangeDesc delete_file_range;
226
                    // must use __set() method to make sure __isset is true
227
1.38k
                    delete_file_range.__set_fs_name(_range.fs_name);
228
1.38k
                    delete_file_range.path = delete_file.path;
229
1.38k
                    delete_file_range.start_offset = 0;
230
1.38k
                    delete_file_range.size = -1;
231
1.38k
                    delete_file_range.file_size = -1;
232
                    //read position delete file base on delete_file_range , generate DeleteFile , add DeleteFile to kv_cache
233
1.38k
                    create_status = _read_position_delete_file(&delete_file_range, position_delete);
234
235
1.38k
                    if (!create_status) {
236
0
                        return nullptr;
237
0
                    }
238
239
1.38k
                    return position_delete;
240
1.38k
                });
241
5.26k
        if (create_status.is<ErrorCode::END_OF_FILE>()) {
242
0
            continue;
243
5.26k
        } else if (!create_status.ok()) {
244
0
            return create_status;
245
0
        }
246
247
5.26k
        DeleteFile& delete_file_map = *((DeleteFile*)delete_file_cache);
248
5.26k
        auto get_value = [&](const auto& v) {
249
3.36k
            DeleteRows* row_ids = v.second.get();
250
3.36k
            if (!row_ids->empty()) {
251
3.36k
                delete_rows_array.emplace_back(row_ids);
252
3.36k
                num_delete_rows += row_ids->size();
253
3.36k
            }
254
3.36k
        };
255
5.26k
        delete_file_map.if_contains(data_file_path, get_value);
256
5.26k
    }
257
    // Use a KV cache to store the delete rows corresponding to a data file path.
258
    // The Parquet/ORC reader holds a reference (pointer) to this cached entry.
259
    // This allows delete rows to be reused when a single data file is split into
260
    // multiple splits, avoiding excessive memory usage when delete rows are large.
261
1.64k
    if (num_delete_rows > 0) {
262
1.28k
        SCOPED_TIMER(_iceberg_profile.delete_rows_sort_time);
263
1.28k
        _iceberg_delete_rows =
264
1.28k
                _kv_cache->get<DeleteRows>(data_file_path,
265
1.28k
                                           [&]() -> DeleteRows* {
266
1.28k
                                               auto* data_file_position_delete = new DeleteRows;
267
1.28k
                                               _sort_delete_rows(delete_rows_array, num_delete_rows,
268
1.28k
                                                                 *data_file_position_delete);
269
270
1.28k
                                               return data_file_position_delete;
271
1.28k
                                           }
272
273
1.28k
                );
274
1.28k
        set_delete_rows();
275
1.28k
        COUNTER_UPDATE(_iceberg_profile.num_delete_rows, num_delete_rows);
276
1.28k
    }
277
1.64k
    return Status::OK();
278
1.64k
}
279
280
IcebergTableReader::PositionDeleteRange IcebergTableReader::_get_range(
281
260
        const ColumnDictI32& file_path_column) {
282
260
    IcebergTableReader::PositionDeleteRange range;
283
260
    size_t read_rows = file_path_column.get_data().size();
284
260
    const int* code_path = file_path_column.get_data().data();
285
260
    const int* code_path_start = code_path;
286
260
    const int* code_path_end = code_path + read_rows;
287
520
    while (code_path < code_path_end) {
288
260
        int code = code_path[0];
289
260
        const int* code_end = std::upper_bound(code_path, code_path_end, code);
290
260
        range.data_file_path.emplace_back(file_path_column.get_value(code).to_string());
291
260
        range.range.emplace_back(code_path - code_path_start, code_end - code_path_start);
292
260
        code_path = code_end;
293
260
    }
294
260
    return range;
295
260
}
296
297
IcebergTableReader::PositionDeleteRange IcebergTableReader::_get_range(
298
1.90k
        const ColumnString& file_path_column) {
299
1.90k
    IcebergTableReader::PositionDeleteRange range;
300
1.90k
    size_t read_rows = file_path_column.size();
301
1.90k
    size_t index = 0;
302
7.92k
    while (index < read_rows) {
303
6.01k
        StringRef data_path = file_path_column.get_data_at(index);
304
6.01k
        size_t left = index - 1;
305
6.01k
        size_t right = read_rows;
306
54.2k
        while (left + 1 != right) {
307
48.2k
            size_t mid = left + (right - left) / 2;
308
48.2k
            if (file_path_column.get_data_at(mid) > data_path) {
309
30.1k
                right = mid;
310
30.1k
            } else {
311
18.0k
                left = mid;
312
18.0k
            }
313
48.2k
        }
314
6.01k
        range.data_file_path.emplace_back(data_path.to_string());
315
6.01k
        range.range.emplace_back(index, left + 1);
316
6.01k
        index = left + 1;
317
6.01k
    }
318
1.90k
    return range;
319
1.90k
}
320
321
/**
322
 * https://iceberg.apache.org/spec/#position-delete-files
323
 * The rows in the delete file must be sorted by file_path then position to optimize filtering rows while scanning.
324
 * Sorting by file_path allows filter pushdown by file in columnar storage formats.
325
 * Sorting by position allows filtering rows while scanning, to avoid keeping deletes in memory.
326
 */
327
void IcebergTableReader::_sort_delete_rows(
328
        const std::vector<std::vector<int64_t>*>& delete_rows_array, int64_t num_delete_rows,
329
1.28k
        std::vector<int64_t>& result) {
330
1.28k
    if (delete_rows_array.empty()) {
331
0
        return;
332
0
    }
333
1.28k
    if (delete_rows_array.size() == 1) {
334
596
        result.resize(num_delete_rows);
335
596
        memcpy(result.data(), delete_rows_array.front()->data(), sizeof(int64_t) * num_delete_rows);
336
596
        return;
337
596
    }
338
690
    if (delete_rows_array.size() == 2) {
339
0
        result.resize(num_delete_rows);
340
0
        std::merge(delete_rows_array.front()->begin(), delete_rows_array.front()->end(),
341
0
                   delete_rows_array.back()->begin(), delete_rows_array.back()->end(),
342
0
                   result.begin());
343
0
        return;
344
0
    }
345
346
690
    using vec_pair = std::pair<std::vector<int64_t>::iterator, std::vector<int64_t>::iterator>;
347
690
    result.resize(num_delete_rows);
348
690
    auto row_id_iter = result.begin();
349
690
    auto iter_end = result.end();
350
690
    std::vector<vec_pair> rows_array;
351
2.76k
    for (auto* rows : delete_rows_array) {
352
2.76k
        if (!rows->empty()) {
353
2.76k
            rows_array.emplace_back(rows->begin(), rows->end());
354
2.76k
        }
355
2.76k
    }
356
690
    size_t array_size = rows_array.size();
357
332k
    while (row_id_iter != iter_end) {
358
332k
        int64_t min_index = 0;
359
332k
        int64_t min = *rows_array[0].first;
360
1.65M
        for (size_t i = 0; i < array_size; ++i) {
361
1.32M
            if (*rows_array[i].first < min) {
362
326k
                min_index = i;
363
326k
                min = *rows_array[i].first;
364
326k
            }
365
1.32M
        }
366
332k
        *row_id_iter++ = min;
367
332k
        rows_array[min_index].first++;
368
332k
        if (UNLIKELY(rows_array[min_index].first == rows_array[min_index].second)) {
369
2.76k
            rows_array.erase(rows_array.begin() + min_index);
370
2.76k
            array_size--;
371
2.76k
        }
372
332k
    }
373
690
}
374
375
void IcebergTableReader::_gen_position_delete_file_range(Block& block, DeleteFile* position_delete,
376
                                                         size_t read_rows,
377
2.16k
                                                         bool file_path_column_dictionary_coded) {
378
2.16k
    SCOPED_TIMER(_iceberg_profile.parse_delete_file_time);
379
    // todo: maybe do not need to build name to index map every time
380
2.16k
    auto name_to_pos_map = block.get_name_to_pos_map();
381
2.16k
    ColumnPtr path_column = block.get_by_position(name_to_pos_map[ICEBERG_FILE_PATH]).column;
382
2.16k
    DCHECK_EQ(path_column->size(), read_rows);
383
2.16k
    ColumnPtr pos_column = block.get_by_position(name_to_pos_map[ICEBERG_ROW_POS]).column;
384
2.16k
    using ColumnType = typename PrimitiveTypeTraits<TYPE_BIGINT>::ColumnType;
385
2.16k
    const int64_t* src_data = assert_cast<const ColumnType&>(*pos_column).get_data().data();
386
2.16k
    IcebergTableReader::PositionDeleteRange range;
387
2.16k
    if (file_path_column_dictionary_coded) {
388
260
        range = _get_range(assert_cast<const ColumnDictI32&>(*path_column));
389
1.90k
    } else {
390
1.90k
        range = _get_range(assert_cast<const ColumnString&>(*path_column));
391
1.90k
    }
392
8.44k
    for (int i = 0; i < range.range.size(); ++i) {
393
6.27k
        std::string key = range.data_file_path[i];
394
6.27k
        auto iter = position_delete->find(key);
395
6.27k
        DeleteRows* delete_rows;
396
6.27k
        if (iter == position_delete->end()) {
397
6.27k
            delete_rows = new DeleteRows;
398
6.27k
            std::unique_ptr<DeleteRows> delete_rows_ptr(delete_rows);
399
6.27k
            (*position_delete)[key] = std::move(delete_rows_ptr);
400
6.27k
        } else {
401
0
            delete_rows = iter->second.get();
402
0
        }
403
6.27k
        const int64_t* cpy_start = src_data + range.range[i].first;
404
6.27k
        const int64_t cpy_count = range.range[i].second - range.range[i].first;
405
6.27k
        int64_t origin_size = delete_rows->size();
406
6.27k
        delete_rows->resize(origin_size + cpy_count);
407
6.27k
        int64_t* dest_position = &(*delete_rows)[origin_size];
408
6.27k
        memcpy(dest_position, cpy_start, cpy_count * sizeof(int64_t));
409
6.27k
    }
410
2.16k
}
411
412
Status IcebergParquetReader::init_reader(
413
        const std::vector<std::string>& file_col_names,
414
        std::unordered_map<std::string, uint32_t>* col_name_to_block_idx,
415
        const VExprContextSPtrs& conjuncts,
416
        phmap::flat_hash_map<int, std::vector<std::shared_ptr<ColumnPredicate>>>&
417
                slot_id_to_predicates,
418
        const TupleDescriptor* tuple_descriptor, const RowDescriptor* row_descriptor,
419
        const std::unordered_map<std::string, int>* colname_to_slot_id,
420
        const VExprContextSPtrs* not_single_slot_filter_conjuncts,
421
17.5k
        const std::unordered_map<int, VExprContextSPtrs>* slot_id_to_filter_conjuncts) {
422
17.5k
    _file_format = Fileformat::PARQUET;
423
17.5k
    _col_name_to_block_idx = col_name_to_block_idx;
424
17.5k
    auto* parquet_reader = static_cast<ParquetReader*>(_file_format_reader.get());
425
17.5k
    RETURN_IF_ERROR(parquet_reader->get_file_metadata_schema(&_data_file_field_desc));
426
17.5k
    DCHECK(_data_file_field_desc != nullptr);
427
428
17.5k
    auto column_id_result = _create_column_ids(_data_file_field_desc, tuple_descriptor);
429
17.5k
    auto& column_ids = column_id_result.column_ids;
430
17.5k
    const auto& filter_column_ids = column_id_result.filter_column_ids;
431
432
17.5k
    RETURN_IF_ERROR(init_row_filters());
433
17.5k
    _all_required_col_names = file_col_names;
434
435
17.5k
    if (!_params.__isset.history_schema_info || _params.history_schema_info.empty()) [[unlikely]] {
436
1
        RETURN_IF_ERROR(BuildTableInfoUtil::by_parquet_name(
437
1
                tuple_descriptor, *_data_file_field_desc, table_info_node_ptr));
438
17.5k
    } else {
439
17.5k
        std::set<std::string> read_col_name_set(file_col_names.begin(), file_col_names.end());
440
441
17.5k
        bool exist_field_id = true;
442
138k
        for (int idx = 0; idx < _data_file_field_desc->size(); idx++) {
443
121k
            if (_data_file_field_desc->get_column(idx)->field_id == -1) {
444
                // the data file may be from hive table migrated to iceberg, field id is missing
445
2
                exist_field_id = false;
446
2
                break;
447
2
            }
448
121k
        }
449
17.5k
        const auto& table_schema = _params.history_schema_info.front().root_field;
450
451
17.5k
        table_info_node_ptr = std::make_shared<TableSchemaChangeHelper::StructNode>();
452
17.5k
        if (exist_field_id) {
453
            // id -> table column name. columns that need read data file.
454
17.4k
            std::unordered_map<int, std::shared_ptr<schema::external::TField>> id_to_table_field;
455
54.8k
            for (const auto& table_field : table_schema.fields) {
456
54.8k
                auto field = table_field.field_ptr;
457
54.8k
                DCHECK(field->__isset.name);
458
54.8k
                if (!read_col_name_set.contains(field->name)) {
459
2.42k
                    continue;
460
2.42k
                }
461
52.4k
                id_to_table_field.emplace(field->id, field);
462
52.4k
            }
463
464
138k
            for (int idx = 0; idx < _data_file_field_desc->size(); idx++) {
465
121k
                const auto& data_file_field = _data_file_field_desc->get_column(idx);
466
121k
                auto data_file_column_id = _data_file_field_desc->get_column(idx)->field_id;
467
468
121k
                if (id_to_table_field.contains(data_file_column_id)) {
469
49.6k
                    const auto& table_field = id_to_table_field[data_file_column_id];
470
471
49.6k
                    std::shared_ptr<TableSchemaChangeHelper::Node> field_node = nullptr;
472
49.6k
                    RETURN_IF_ERROR(BuildTableInfoUtil::by_parquet_field_id(
473
49.6k
                            *table_field, *data_file_field, exist_field_id, field_node));
474
49.6k
                    table_info_node_ptr->add_children(table_field->name, data_file_field->name,
475
49.6k
                                                      field_node);
476
477
49.6k
                    _id_to_block_column_name.emplace(data_file_column_id, table_field->name);
478
49.6k
                    id_to_table_field.erase(data_file_column_id);
479
71.6k
                } else if (_equality_delete_col_ids.contains(data_file_column_id)) {
480
                    // Columns that need to be read for equality delete.
481
318
                    const static std::string EQ_DELETE_PRE = "__equality_delete_column__";
482
483
                    // Construct table column names that avoid duplication with current table schema.
484
                    // As the columns currently being read may have been deleted in the latest
485
                    // table structure or have undergone a series of schema changes...
486
318
                    std::string table_column_name = EQ_DELETE_PRE + data_file_field->name;
487
318
                    table_info_node_ptr->add_children(
488
318
                            table_column_name, data_file_field->name,
489
318
                            std::make_shared<TableSchemaChangeHelper::ConstNode>());
490
491
318
                    _id_to_block_column_name.emplace(data_file_column_id, table_column_name);
492
318
                    _expand_col_names.emplace_back(table_column_name);
493
318
                    auto expand_data_type = make_nullable(data_file_field->data_type);
494
318
                    _expand_columns.emplace_back(
495
318
                            ColumnWithTypeAndName {expand_data_type->create_column(),
496
318
                                                   expand_data_type, table_column_name});
497
498
318
                    _all_required_col_names.emplace_back(table_column_name);
499
318
                    column_ids.insert(data_file_field->get_column_id());
500
318
                }
501
121k
            }
502
17.4k
            for (const auto& [id, table_field] : id_to_table_field) {
503
2.80k
                table_info_node_ptr->add_not_exist_children(table_field->name);
504
2.80k
            }
505
17.4k
        } else {
506
66
            if (!_equality_delete_col_ids.empty()) [[unlikely]] {
507
0
                return Status::InternalError(
508
0
                        "Can not read missing field id data file when have equality delete");
509
0
            }
510
66
            std::map<std::string, size_t> file_column_idx_map;
511
74
            for (size_t idx = 0; idx < _data_file_field_desc->size(); idx++) {
512
8
                file_column_idx_map.emplace(_data_file_field_desc->get_column(idx)->name, idx);
513
8
            }
514
515
66
            for (const auto& table_field : table_schema.fields) {
516
2
                DCHECK(table_field.__isset.field_ptr);
517
2
                DCHECK(table_field.field_ptr->__isset.name);
518
2
                const auto& table_column_name = table_field.field_ptr->name;
519
2
                if (!read_col_name_set.contains(table_column_name)) {
520
0
                    continue;
521
0
                }
522
2
                if (!table_field.field_ptr->__isset.name_mapping ||
523
2
                    table_field.field_ptr->name_mapping.size() == 0) {
524
2
                    return Status::DataQualityError(
525
2
                            "name_mapping must be set when read missing field id data file.");
526
2
                }
527
0
                bool have_mapping = false;
528
0
                for (const auto& mapped_name : table_field.field_ptr->name_mapping) {
529
0
                    if (file_column_idx_map.contains(mapped_name)) {
530
0
                        std::shared_ptr<TableSchemaChangeHelper::Node> field_node = nullptr;
531
0
                        const auto& file_field = _data_file_field_desc->get_column(
532
0
                                file_column_idx_map.at(mapped_name));
533
0
                        RETURN_IF_ERROR(BuildTableInfoUtil::by_parquet_field_id(
534
0
                                *table_field.field_ptr, *file_field, exist_field_id, field_node));
535
0
                        table_info_node_ptr->add_children(table_column_name, file_field->name,
536
0
                                                          field_node);
537
0
                        have_mapping = true;
538
0
                        break;
539
0
                    }
540
0
                }
541
0
                if (!have_mapping) {
542
0
                    table_info_node_ptr->add_not_exist_children(table_column_name);
543
0
                }
544
0
            }
545
66
        }
546
17.5k
    }
547
548
17.5k
    return parquet_reader->init_reader(
549
17.5k
            _all_required_col_names, _col_name_to_block_idx, conjuncts, slot_id_to_predicates,
550
17.5k
            tuple_descriptor, row_descriptor, colname_to_slot_id, not_single_slot_filter_conjuncts,
551
17.5k
            slot_id_to_filter_conjuncts, table_info_node_ptr, true, column_ids, filter_column_ids);
552
17.5k
}
553
554
ColumnIdResult IcebergParquetReader::_create_column_ids(const FieldDescriptor* field_desc,
555
17.4k
                                                        const TupleDescriptor* tuple_descriptor) {
556
    // First, assign column IDs to the field descriptor
557
17.4k
    auto* mutable_field_desc = const_cast<FieldDescriptor*>(field_desc);
558
17.4k
    mutable_field_desc->assign_ids();
559
560
    // map top-level table column iceberg_id -> FieldSchema*
561
17.4k
    std::unordered_map<int, const FieldSchema*> iceberg_id_to_field_schema_map;
562
563
139k
    for (int i = 0; i < field_desc->size(); ++i) {
564
121k
        auto field_schema = field_desc->get_column(i);
565
121k
        if (!field_schema) continue;
566
567
121k
        int iceberg_id = field_schema->field_id;
568
121k
        iceberg_id_to_field_schema_map[iceberg_id] = field_schema;
569
121k
    }
570
571
17.4k
    std::set<uint64_t> column_ids;
572
17.4k
    std::set<uint64_t> filter_column_ids;
573
574
    // helper to process access paths for a given top-level parquet field
575
17.4k
    auto process_access_paths = [](const FieldSchema* parquet_field,
576
17.4k
                                   const std::vector<TColumnAccessPath>& access_paths,
577
17.4k
                                   std::set<uint64_t>& out_ids) {
578
15.7k
        process_nested_access_paths(
579
15.7k
                parquet_field, access_paths, out_ids,
580
15.7k
                [](const FieldSchema* field) { return field->get_column_id(); },
581
15.7k
                [](const FieldSchema* field) { return field->get_max_column_id(); },
582
15.7k
                IcebergParquetNestedColumnUtils::extract_nested_column_ids);
583
15.7k
    };
584
585
52.7k
    for (const auto* slot : tuple_descriptor->slots()) {
586
52.7k
        auto it = iceberg_id_to_field_schema_map.find(slot->col_unique_id());
587
52.7k
        if (it == iceberg_id_to_field_schema_map.end()) {
588
            // Column not found in file (e.g., partition column, added column)
589
3.05k
            continue;
590
3.05k
        }
591
49.6k
        auto field_schema = it->second;
592
593
        // primitive (non-nested) types: direct mapping by name
594
49.6k
        if ((slot->col_type() != TYPE_STRUCT && slot->col_type() != TYPE_ARRAY &&
595
49.6k
             slot->col_type() != TYPE_MAP)) {
596
35.3k
            column_ids.insert(field_schema->column_id);
597
598
35.3k
            if (slot->is_predicate()) {
599
5.68k
                filter_column_ids.insert(field_schema->column_id);
600
5.68k
            }
601
35.3k
            continue;
602
35.3k
        }
603
604
        // complex types:
605
14.2k
        const auto& all_access_paths = slot->all_access_paths();
606
14.2k
        process_access_paths(field_schema, all_access_paths, column_ids);
607
608
14.2k
        const auto& predicate_access_paths = slot->predicate_access_paths();
609
14.2k
        if (!predicate_access_paths.empty()) {
610
1.57k
            process_access_paths(field_schema, predicate_access_paths, filter_column_ids);
611
1.57k
        }
612
14.2k
    }
613
17.4k
    return ColumnIdResult(std::move(column_ids), std::move(filter_column_ids));
614
17.4k
}
615
616
Status IcebergParquetReader ::_read_position_delete_file(const TFileRangeDesc* delete_range,
617
602
                                                         DeleteFile* position_delete) {
618
602
    ParquetReader parquet_delete_reader(_profile, _params, *delete_range,
619
602
                                        READ_DELETE_FILE_BATCH_SIZE, &_state->timezone_obj(),
620
602
                                        _io_ctx, _state, _meta_cache);
621
602
    phmap::flat_hash_map<int, std::vector<std::shared_ptr<ColumnPredicate>>> tmp;
622
602
    RETURN_IF_ERROR(parquet_delete_reader.init_reader(
623
602
            delete_file_col_names,
624
602
            const_cast<std::unordered_map<std::string, uint32_t>*>(&DELETE_COL_NAME_TO_BLOCK_IDX),
625
602
            {}, tmp, nullptr, nullptr, nullptr, nullptr, nullptr,
626
602
            TableSchemaChangeHelper::ConstNode::get_instance(), false));
627
628
602
    std::unordered_map<std::string, std::tuple<std::string, const SlotDescriptor*>>
629
602
            partition_columns;
630
602
    std::unordered_map<std::string, VExprContextSPtr> missing_columns;
631
602
    RETURN_IF_ERROR(parquet_delete_reader.set_fill_columns(partition_columns, missing_columns));
632
633
602
    const tparquet::FileMetaData* meta_data = parquet_delete_reader.get_meta_data();
634
602
    bool dictionary_coded = true;
635
602
    for (const auto& row_group : meta_data->row_groups) {
636
602
        const auto& column_chunk = row_group.columns[ICEBERG_FILE_PATH_INDEX];
637
602
        if (!(column_chunk.__isset.meta_data && has_dict_page(column_chunk.meta_data))) {
638
342
            dictionary_coded = false;
639
342
            break;
640
342
        }
641
602
    }
642
602
    DataTypePtr data_type_file_path {new DataTypeString};
643
602
    DataTypePtr data_type_pos {new DataTypeInt64};
644
602
    bool eof = false;
645
1.20k
    while (!eof) {
646
602
        Block block = {dictionary_coded
647
602
                               ? ColumnWithTypeAndName {ColumnDictI32::create(
648
260
                                                                FieldType::OLAP_FIELD_TYPE_VARCHAR),
649
260
                                                        data_type_file_path, ICEBERG_FILE_PATH}
650
602
                               : ColumnWithTypeAndName {data_type_file_path, ICEBERG_FILE_PATH},
651
652
602
                       {data_type_pos, ICEBERG_ROW_POS}};
653
602
        size_t read_rows = 0;
654
602
        RETURN_IF_ERROR(parquet_delete_reader.get_next_block(&block, &read_rows, &eof));
655
656
602
        if (read_rows <= 0) {
657
0
            break;
658
0
        }
659
602
        _gen_position_delete_file_range(block, position_delete, read_rows, dictionary_coded);
660
602
    }
661
602
    return Status::OK();
662
602
};
663
664
Status IcebergOrcReader::init_reader(
665
        const std::vector<std::string>& file_col_names,
666
        std::unordered_map<std::string, uint32_t>* col_name_to_block_idx,
667
        const VExprContextSPtrs& conjuncts, const TupleDescriptor* tuple_descriptor,
668
        const RowDescriptor* row_descriptor,
669
        const std::unordered_map<std::string, int>* colname_to_slot_id,
670
        const VExprContextSPtrs* not_single_slot_filter_conjuncts,
671
5.99k
        const std::unordered_map<int, VExprContextSPtrs>* slot_id_to_filter_conjuncts) {
672
5.99k
    _file_format = Fileformat::ORC;
673
5.99k
    _col_name_to_block_idx = col_name_to_block_idx;
674
5.99k
    auto* orc_reader = static_cast<OrcReader*>(_file_format_reader.get());
675
5.99k
    RETURN_IF_ERROR(orc_reader->get_file_type(&_data_file_type_desc));
676
5.99k
    std::vector<std::string> data_file_col_names;
677
5.99k
    std::vector<DataTypePtr> data_file_col_types;
678
5.99k
    RETURN_IF_ERROR(orc_reader->get_parsed_schema(&data_file_col_names, &data_file_col_types));
679
680
5.99k
    auto column_id_result = _create_column_ids(_data_file_type_desc, tuple_descriptor);
681
5.99k
    auto& column_ids = column_id_result.column_ids;
682
5.99k
    const auto& filter_column_ids = column_id_result.filter_column_ids;
683
684
5.99k
    RETURN_IF_ERROR(init_row_filters());
685
686
5.99k
    _all_required_col_names = file_col_names;
687
5.99k
    if (!_params.__isset.history_schema_info || _params.history_schema_info.empty()) [[unlikely]] {
688
1
        RETURN_IF_ERROR(BuildTableInfoUtil::by_orc_name(tuple_descriptor, _data_file_type_desc,
689
1
                                                        table_info_node_ptr));
690
5.99k
    } else {
691
5.99k
        std::set<std::string> read_col_name_set(file_col_names.begin(), file_col_names.end());
692
693
5.99k
        bool exist_field_id = true;
694
48.3k
        for (size_t idx = 0; idx < _data_file_type_desc->getSubtypeCount(); idx++) {
695
42.3k
            if (!_data_file_type_desc->getSubtype(idx)->hasAttributeKey(ICEBERG_ORC_ATTRIBUTE)) {
696
0
                exist_field_id = false;
697
0
                break;
698
0
            }
699
42.3k
        }
700
701
5.99k
        const auto& table_schema = _params.history_schema_info.front().root_field;
702
5.99k
        table_info_node_ptr = std::make_shared<TableSchemaChangeHelper::StructNode>();
703
5.99k
        if (exist_field_id) {
704
            // id -> table column name. columns that need read data file.
705
5.98k
            std::unordered_map<int, std::shared_ptr<schema::external::TField>> id_to_table_field;
706
30.2k
            for (const auto& table_field : table_schema.fields) {
707
30.2k
                auto field = table_field.field_ptr;
708
30.2k
                DCHECK(field->__isset.name);
709
30.2k
                if (!read_col_name_set.contains(field->name)) {
710
468
                    continue;
711
468
                }
712
713
29.8k
                id_to_table_field.emplace(field->id, field);
714
29.8k
            }
715
716
48.3k
            for (int idx = 0; idx < _data_file_type_desc->getSubtypeCount(); idx++) {
717
42.3k
                const auto& data_file_field = _data_file_type_desc->getSubtype(idx);
718
42.3k
                auto data_file_column_id =
719
42.3k
                        std::stoi(data_file_field->getAttributeValue(ICEBERG_ORC_ATTRIBUTE));
720
42.3k
                auto const& file_column_name = _data_file_type_desc->getFieldName(idx);
721
722
42.3k
                if (id_to_table_field.contains(data_file_column_id)) {
723
28.1k
                    const auto& table_field = id_to_table_field[data_file_column_id];
724
725
28.1k
                    std::shared_ptr<TableSchemaChangeHelper::Node> field_node = nullptr;
726
28.1k
                    RETURN_IF_ERROR(BuildTableInfoUtil::by_orc_field_id(
727
28.1k
                            *table_field, data_file_field, ICEBERG_ORC_ATTRIBUTE, exist_field_id,
728
28.1k
                            field_node));
729
28.1k
                    table_info_node_ptr->add_children(table_field->name, file_column_name,
730
28.1k
                                                      field_node);
731
732
28.1k
                    _id_to_block_column_name.emplace(data_file_column_id, table_field->name);
733
28.1k
                    id_to_table_field.erase(data_file_column_id);
734
28.1k
                } else if (_equality_delete_col_ids.contains(data_file_column_id)) {
735
                    // Columns that need to be read for equality delete.
736
318
                    const static std::string EQ_DELETE_PRE = "__equality_delete_column__";
737
738
                    // Construct table column names that avoid duplication with current table schema.
739
                    // As the columns currently being read may have been deleted in the latest
740
                    // table structure or have undergone a series of schema changes...
741
318
                    std::string table_column_name = EQ_DELETE_PRE + file_column_name;
742
318
                    table_info_node_ptr->add_children(
743
318
                            table_column_name, file_column_name,
744
318
                            std::make_shared<TableSchemaChangeHelper::ConstNode>());
745
746
318
                    _id_to_block_column_name.emplace(data_file_column_id, table_column_name);
747
318
                    _expand_col_names.emplace_back(table_column_name);
748
749
318
                    auto expand_data_type = make_nullable(data_file_col_types[idx]);
750
318
                    _expand_columns.emplace_back(
751
318
                            ColumnWithTypeAndName {expand_data_type->create_column(),
752
318
                                                   expand_data_type, table_column_name});
753
754
318
                    _all_required_col_names.emplace_back(table_column_name);
755
318
                    column_ids.insert(data_file_field->getColumnId());
756
318
                }
757
42.3k
            }
758
5.98k
            for (const auto& [id, table_field] : id_to_table_field) {
759
1.74k
                table_info_node_ptr->add_not_exist_children(table_field->name);
760
1.74k
            }
761
5.98k
        } else {
762
4
            if (!_equality_delete_col_ids.empty()) [[unlikely]] {
763
0
                return Status::InternalError(
764
0
                        "Can not read missing field id data file when have equality delete");
765
0
            }
766
4
            std::map<std::string, size_t> file_column_idx_map;
767
4
            for (int idx = 0; idx < _data_file_type_desc->getSubtypeCount(); idx++) {
768
0
                auto const& file_column_name = _data_file_type_desc->getFieldName(idx);
769
0
                file_column_idx_map.emplace(file_column_name, idx);
770
0
            }
771
772
4
            for (const auto& table_field : table_schema.fields) {
773
0
                DCHECK(table_field.__isset.field_ptr);
774
0
                DCHECK(table_field.field_ptr->__isset.name);
775
0
                const auto& table_column_name = table_field.field_ptr->name;
776
0
                if (!read_col_name_set.contains(table_column_name)) {
777
0
                    continue;
778
0
                }
779
0
                if (!table_field.field_ptr->__isset.name_mapping ||
780
0
                    table_field.field_ptr->name_mapping.size() == 0) {
781
0
                    return Status::DataQualityError(
782
0
                            "name_mapping must be set when read missing field id data file.");
783
0
                }
784
0
                auto have_mapping = false;
785
0
                for (const auto& mapped_name : table_field.field_ptr->name_mapping) {
786
0
                    if (file_column_idx_map.contains(mapped_name)) {
787
0
                        auto file_column_idx = file_column_idx_map.at(mapped_name);
788
0
                        std::shared_ptr<TableSchemaChangeHelper::Node> field_node = nullptr;
789
0
                        const auto& file_field = _data_file_type_desc->getSubtype(file_column_idx);
790
0
                        RETURN_IF_ERROR(BuildTableInfoUtil::by_orc_field_id(
791
0
                                *table_field.field_ptr, file_field, ICEBERG_ORC_ATTRIBUTE,
792
0
                                exist_field_id, field_node));
793
0
                        table_info_node_ptr->add_children(
794
0
                                table_column_name,
795
0
                                _data_file_type_desc->getFieldName(file_column_idx), field_node);
796
0
                        have_mapping = true;
797
0
                        break;
798
0
                    }
799
0
                }
800
0
                if (!have_mapping) {
801
0
                    table_info_node_ptr->add_not_exist_children(table_column_name);
802
0
                }
803
0
            }
804
4
        }
805
5.99k
    }
806
807
5.99k
    return orc_reader->init_reader(&_all_required_col_names, _col_name_to_block_idx, conjuncts,
808
5.99k
                                   false, tuple_descriptor, row_descriptor,
809
5.99k
                                   not_single_slot_filter_conjuncts, slot_id_to_filter_conjuncts,
810
5.99k
                                   table_info_node_ptr, column_ids, filter_column_ids);
811
5.99k
}
812
813
ColumnIdResult IcebergOrcReader::_create_column_ids(const orc::Type* orc_type,
814
5.99k
                                                    const TupleDescriptor* tuple_descriptor) {
815
    // map top-level table column iceberg_id -> orc::Type*
816
5.99k
    std::unordered_map<int, const orc::Type*> iceberg_id_to_orc_type_map;
817
48.4k
    for (uint64_t i = 0; i < orc_type->getSubtypeCount(); ++i) {
818
42.4k
        auto orc_sub_type = orc_type->getSubtype(i);
819
42.4k
        if (!orc_sub_type) continue;
820
821
42.4k
        if (!orc_sub_type->hasAttributeKey(ICEBERG_ORC_ATTRIBUTE)) {
822
0
            continue;
823
0
        }
824
42.4k
        int iceberg_id = std::stoi(orc_sub_type->getAttributeValue(ICEBERG_ORC_ATTRIBUTE));
825
42.4k
        iceberg_id_to_orc_type_map[iceberg_id] = orc_sub_type;
826
42.4k
    }
827
828
5.99k
    std::set<uint64_t> column_ids;
829
5.99k
    std::set<uint64_t> filter_column_ids;
830
831
    // helper to process access paths for a given top-level orc field
832
5.99k
    auto process_access_paths = [](const orc::Type* orc_field,
833
5.99k
                                   const std::vector<TColumnAccessPath>& access_paths,
834
14.8k
                                   std::set<uint64_t>& out_ids) {
835
14.8k
        process_nested_access_paths(
836
14.8k
                orc_field, access_paths, out_ids,
837
14.8k
                [](const orc::Type* type) { return type->getColumnId(); },
838
14.8k
                [](const orc::Type* type) { return type->getMaximumColumnId(); },
839
14.8k
                IcebergOrcNestedColumnUtils::extract_nested_column_ids);
840
14.8k
    };
841
842
30.0k
    for (const auto* slot : tuple_descriptor->slots()) {
843
30.0k
        auto it = iceberg_id_to_orc_type_map.find(slot->col_unique_id());
844
30.0k
        if (it == iceberg_id_to_orc_type_map.end()) {
845
            // Column not found in file
846
1.97k
            continue;
847
1.97k
        }
848
28.1k
        const orc::Type* orc_field = it->second;
849
850
        // primitive (non-nested) types
851
28.1k
        if ((slot->col_type() != TYPE_STRUCT && slot->col_type() != TYPE_ARRAY &&
852
28.1k
             slot->col_type() != TYPE_MAP)) {
853
14.8k
            column_ids.insert(orc_field->getColumnId());
854
14.8k
            if (slot->is_predicate()) {
855
2.29k
                filter_column_ids.insert(orc_field->getColumnId());
856
2.29k
            }
857
14.8k
            continue;
858
14.8k
        }
859
860
        // complex types
861
13.3k
        const auto& all_access_paths = slot->all_access_paths();
862
13.3k
        process_access_paths(orc_field, all_access_paths, column_ids);
863
864
13.3k
        const auto& predicate_access_paths = slot->predicate_access_paths();
865
13.3k
        if (!predicate_access_paths.empty()) {
866
1.55k
            process_access_paths(orc_field, predicate_access_paths, filter_column_ids);
867
1.55k
        }
868
13.3k
    }
869
870
5.99k
    return ColumnIdResult(std::move(column_ids), std::move(filter_column_ids));
871
5.99k
}
872
873
Status IcebergOrcReader::_read_position_delete_file(const TFileRangeDesc* delete_range,
874
780
                                                    DeleteFile* position_delete) {
875
780
    OrcReader orc_delete_reader(_profile, _state, _params, *delete_range,
876
780
                                READ_DELETE_FILE_BATCH_SIZE, _state->timezone(), _io_ctx,
877
780
                                _meta_cache);
878
780
    RETURN_IF_ERROR(orc_delete_reader.init_reader(
879
780
            &delete_file_col_names,
880
780
            const_cast<std::unordered_map<std::string, uint32_t>*>(&DELETE_COL_NAME_TO_BLOCK_IDX),
881
780
            {}, false, {}, {}, nullptr, nullptr));
882
883
780
    std::unordered_map<std::string, std::tuple<std::string, const SlotDescriptor*>>
884
780
            partition_columns;
885
780
    std::unordered_map<std::string, VExprContextSPtr> missing_columns;
886
780
    RETURN_IF_ERROR(orc_delete_reader.set_fill_columns(partition_columns, missing_columns));
887
888
780
    bool eof = false;
889
780
    DataTypePtr data_type_file_path {new DataTypeString};
890
780
    DataTypePtr data_type_pos {new DataTypeInt64};
891
2.34k
    while (!eof) {
892
1.56k
        Block block = {{data_type_file_path, ICEBERG_FILE_PATH}, {data_type_pos, ICEBERG_ROW_POS}};
893
894
1.56k
        size_t read_rows = 0;
895
1.56k
        RETURN_IF_ERROR(orc_delete_reader.get_next_block(&block, &read_rows, &eof));
896
897
1.56k
        _gen_position_delete_file_range(block, position_delete, read_rows, false);
898
1.56k
    }
899
780
    return Status::OK();
900
780
}
901
902
// Directly read the deletion vector using the `content_offset` and
903
// `content_size_in_bytes` provided by FE in `delete_file_desc`.
904
// These two fields indicate the location of a blob in storage.
905
// Since the current format is `deletion-vector-v1`, which does not
906
// compress any blobs, we can temporarily skip parsing the Puffin footer.
907
Status IcebergTableReader::read_deletion_vector(const std::string& data_file_path,
908
2.36k
                                                const TIcebergDeleteFileDesc& delete_file_desc) {
909
2.36k
    Status create_status = Status::OK();
910
2.36k
    SCOPED_TIMER(_iceberg_profile.delete_files_read_time);
911
2.36k
    _iceberg_delete_rows = _kv_cache->get<DeleteRows>(data_file_path, [&]() -> DeleteRows* {
912
882
        auto* delete_rows = new DeleteRows;
913
914
882
        TFileRangeDesc delete_range;
915
        // must use __set() method to make sure __isset is true
916
882
        delete_range.__set_fs_name(_range.fs_name);
917
882
        delete_range.path = delete_file_desc.path;
918
882
        delete_range.start_offset = delete_file_desc.content_offset;
919
882
        delete_range.size = delete_file_desc.content_size_in_bytes;
920
882
        delete_range.file_size = -1;
921
922
        // We may consider caching the DeletionVectorReader when reading Puffin files,
923
        // where the underlying reader is an `InMemoryFileReader` and a single data file is
924
        // split into multiple splits. However, we need to ensure that the underlying
925
        // reader supports multi-threaded access.
926
882
        DeletionVectorReader dv_reader(_state, _profile, _params, delete_range, _io_ctx);
927
882
        create_status = dv_reader.open();
928
882
        if (!create_status.ok()) [[unlikely]] {
929
0
            return nullptr;
930
0
        }
931
932
882
        size_t buffer_size = delete_range.size;
933
882
        std::vector<char> buf(buffer_size);
934
882
        if (buffer_size < 12) [[unlikely]] {
935
            // Minimum size: 4 bytes length + 4 bytes magic + 4 bytes CRC32
936
0
            create_status = Status::DataQualityError("Deletion vector file size too small: {}",
937
0
                                                     buffer_size);
938
0
            return nullptr;
939
0
        }
940
941
882
        create_status = dv_reader.read_at(delete_range.start_offset, {buf.data(), buffer_size});
942
882
        if (!create_status) [[unlikely]] {
943
0
            return nullptr;
944
0
        }
945
        // The serialized blob contains:
946
        //
947
        // Combined length of the vector and magic bytes stored as 4 bytes, big-endian
948
        // A 4-byte magic sequence, D1 D3 39 64
949
        // The vector, serialized as described below
950
        // A CRC-32 checksum of the magic bytes and serialized vector as 4 bytes, big-endian
951
952
882
        auto total_length = BigEndian::Load32(buf.data());
953
882
        if (total_length + 8 != buffer_size) [[unlikely]] {
954
0
            create_status = Status::DataQualityError(
955
0
                    "Deletion vector length mismatch, expected: {}, actual: {}", total_length + 8,
956
0
                    buffer_size);
957
0
            return nullptr;
958
0
        }
959
960
882
        constexpr static char MAGIC_NUMBER[] = {'\xD1', '\xD3', '\x39', '\x64'};
961
882
        if (memcmp(buf.data() + sizeof(total_length), MAGIC_NUMBER, 4)) [[unlikely]] {
962
0
            create_status = Status::DataQualityError("Deletion vector magic number mismatch");
963
0
            return nullptr;
964
0
        }
965
966
882
        roaring::Roaring64Map bitmap;
967
882
        SCOPED_TIMER(_iceberg_profile.parse_delete_file_time);
968
882
        try {
969
882
            bitmap = roaring::Roaring64Map::readSafe(buf.data() + 8, buffer_size - 12);
970
882
        } catch (const std::runtime_error& e) {
971
0
            create_status = Status::DataQualityError("Decode roaring bitmap failed, {}", e.what());
972
0
            return nullptr;
973
0
        }
974
        // skip CRC-32 checksum
975
976
886
        delete_rows->reserve(bitmap.cardinality());
977
5.04M
        for (auto it = bitmap.begin(); it != bitmap.end(); it++) {
978
5.03M
            delete_rows->push_back(*it);
979
5.03M
        }
980
886
        COUNTER_UPDATE(_iceberg_profile.num_delete_rows, delete_rows->size());
981
886
        return delete_rows;
982
882
    });
983
984
2.36k
    RETURN_IF_ERROR(create_status);
985
2.36k
    if (!_iceberg_delete_rows->empty()) [[likely]] {
986
2.36k
        set_delete_rows();
987
2.36k
    }
988
2.36k
    return Status::OK();
989
2.36k
}
990
991
// Similar to the code structure of IcebergOrcReader::_process_equality_delete,
992
// but considering the significant differences in how parquet/orc obtains
993
// attributes/column IDs, it is not easy to combine them.
994
Status IcebergParquetReader::_process_equality_delete(
995
670
        const std::vector<TIcebergDeleteFileDesc>& delete_files) {
996
670
    std::unordered_map<std::string, std::tuple<std::string, const SlotDescriptor*>>
997
670
            partition_columns;
998
670
    std::unordered_map<std::string, VExprContextSPtr> missing_columns;
999
1000
670
    std::map<int, const FieldSchema*> data_file_id_to_field_schema;
1001
2.68k
    for (int idx = 0; idx < _data_file_field_desc->size(); ++idx) {
1002
2.01k
        auto field_schema = _data_file_field_desc->get_column(idx);
1003
2.01k
        if (_data_file_field_desc->get_column(idx)->field_id == -1) {
1004
0
            return Status::DataQualityError("Iceberg equality delete data file missing field id.");
1005
0
        }
1006
2.01k
        data_file_id_to_field_schema[_data_file_field_desc->get_column(idx)->field_id] =
1007
2.01k
                field_schema;
1008
2.01k
    }
1009
1010
1.52k
    for (const auto& delete_file : delete_files) {
1011
1.52k
        TFileRangeDesc delete_desc;
1012
        // must use __set() method to make sure __isset is true
1013
1.52k
        delete_desc.__set_fs_name(_range.fs_name);
1014
1.52k
        delete_desc.path = delete_file.path;
1015
1.52k
        delete_desc.start_offset = 0;
1016
1.52k
        delete_desc.size = -1;
1017
1.52k
        delete_desc.file_size = -1;
1018
1019
1.52k
        if (!delete_file.__isset.field_ids) [[unlikely]] {
1020
0
            return Status::InternalError(
1021
0
                    "missing delete field ids when reading equality delete file");
1022
0
        }
1023
1.52k
        auto& read_column_field_ids = delete_file.field_ids;
1024
1.52k
        std::set<int> read_column_field_ids_set;
1025
2.37k
        for (const auto& field_id : read_column_field_ids) {
1026
2.37k
            read_column_field_ids_set.insert(field_id);
1027
2.37k
            _equality_delete_col_ids.insert(field_id);
1028
2.37k
        }
1029
1030
1.52k
        auto delete_reader = ParquetReader::create_unique(
1031
1.52k
                _profile, _params, delete_desc, READ_DELETE_FILE_BATCH_SIZE,
1032
1.52k
                &_state->timezone_obj(), _io_ctx, _state, _meta_cache);
1033
1.52k
        RETURN_IF_ERROR(delete_reader->init_schema_reader());
1034
1035
        // the column that to read equality delete file.
1036
        // (delete file may be have extra columns that don't need to read)
1037
1.52k
        std::vector<std::string> delete_col_names;
1038
1.52k
        std::vector<DataTypePtr> delete_col_types;
1039
1.52k
        std::vector<int> delete_col_ids;
1040
1.52k
        std::unordered_map<std::string, uint32_t> delete_col_name_to_block_idx;
1041
1042
1.52k
        const FieldDescriptor* delete_field_desc = nullptr;
1043
1.52k
        RETURN_IF_ERROR(delete_reader->get_file_metadata_schema(&delete_field_desc));
1044
1.52k
        DCHECK(delete_field_desc != nullptr);
1045
1046
1.52k
        auto eq_file_node = std::make_shared<TableSchemaChangeHelper::StructNode>();
1047
2.37k
        for (const auto& delete_file_field : delete_field_desc->get_fields_schema()) {
1048
2.37k
            if (delete_file_field.field_id == -1) [[unlikely]] { // missing delete_file_field id
1049
                // equality delete file must have delete_file_field id to match column.
1050
0
                return Status::DataQualityError(
1051
0
                        "missing delete_file_field id when reading equality delete file");
1052
2.37k
            } else if (read_column_field_ids_set.contains(delete_file_field.field_id)) {
1053
                // the column that need to read.
1054
2.37k
                if (delete_file_field.children.size() > 0) [[unlikely]] { // complex column
1055
0
                    return Status::InternalError(
1056
0
                            "can not support read complex column in equality delete file");
1057
2.37k
                } else if (!data_file_id_to_field_schema.contains(delete_file_field.field_id))
1058
0
                        [[unlikely]] {
1059
0
                    return Status::DataQualityError(
1060
0
                            "can not find delete field id in data file schema when reading "
1061
0
                            "equality delete file");
1062
0
                }
1063
2.37k
                auto data_file_field = data_file_id_to_field_schema[delete_file_field.field_id];
1064
2.37k
                if (data_file_field->data_type->get_primitive_type() !=
1065
2.37k
                    delete_file_field.data_type->get_primitive_type()) [[unlikely]] {
1066
0
                    return Status::NotSupported(
1067
0
                            "Not Support type change in equality delete, field: {}, delete "
1068
0
                            "file type: {}, data file type: {}",
1069
0
                            delete_file_field.field_id, delete_file_field.data_type->get_name(),
1070
0
                            data_file_field->data_type->get_name());
1071
0
                }
1072
1073
2.37k
                std::string filed_lower_name = to_lower(delete_file_field.name);
1074
2.37k
                eq_file_node->add_children(filed_lower_name, delete_file_field.name,
1075
2.37k
                                           std::make_shared<TableSchemaChangeHelper::ScalarNode>());
1076
1077
2.37k
                delete_col_ids.emplace_back(delete_file_field.field_id);
1078
2.37k
                delete_col_names.emplace_back(filed_lower_name);
1079
2.37k
                delete_col_types.emplace_back(make_nullable(delete_file_field.data_type));
1080
1081
2.37k
                read_column_field_ids_set.erase(delete_file_field.field_id);
1082
2.37k
            } else {
1083
                // delete file may be have extra columns that don't need to read
1084
0
            }
1085
2.37k
        }
1086
1.52k
        if (!read_column_field_ids_set.empty()) [[unlikely]] {
1087
0
            return Status::DataQualityError("some field ids not found in equality delete file.");
1088
0
        }
1089
1090
3.89k
        for (uint32_t idx = 0; idx < delete_col_names.size(); ++idx) {
1091
2.37k
            delete_col_name_to_block_idx[delete_col_names[idx]] = idx;
1092
2.37k
        }
1093
1.52k
        phmap::flat_hash_map<int, std::vector<std::shared_ptr<ColumnPredicate>>> tmp;
1094
1.52k
        RETURN_IF_ERROR(delete_reader->init_reader(delete_col_names, &delete_col_name_to_block_idx,
1095
1.52k
                                                   {}, tmp, nullptr, nullptr, nullptr, nullptr,
1096
1.52k
                                                   nullptr, eq_file_node, false));
1097
1.52k
        RETURN_IF_ERROR(delete_reader->set_fill_columns(partition_columns, missing_columns));
1098
1099
1.52k
        if (!_equality_delete_block_map.contains(delete_col_ids)) {
1100
852
            _equality_delete_block_map.emplace(delete_col_ids, _equality_delete_blocks.size());
1101
852
            Block block;
1102
852
            _generate_equality_delete_block(&block, delete_col_names, delete_col_types);
1103
852
            _equality_delete_blocks.emplace_back(block);
1104
852
        }
1105
1.52k
        Block& eq_file_block = _equality_delete_blocks[_equality_delete_block_map[delete_col_ids]];
1106
1.52k
        bool eof = false;
1107
3.04k
        while (!eof) {
1108
1.52k
            Block tmp_block;
1109
1.52k
            _generate_equality_delete_block(&tmp_block, delete_col_names, delete_col_types);
1110
1.52k
            size_t read_rows = 0;
1111
1.52k
            RETURN_IF_ERROR(delete_reader->get_next_block(&tmp_block, &read_rows, &eof));
1112
1.52k
            if (read_rows > 0) {
1113
1.52k
                MutableBlock mutable_block(&eq_file_block);
1114
1.52k
                RETURN_IF_ERROR(mutable_block.merge(tmp_block));
1115
1.52k
            }
1116
1.52k
        }
1117
1.52k
    }
1118
1119
852
    for (const auto& [delete_col_ids, block_idx] : _equality_delete_block_map) {
1120
852
        auto& eq_file_block = _equality_delete_blocks[block_idx];
1121
852
        auto equality_delete_impl =
1122
852
                EqualityDeleteBase::get_delete_impl(&eq_file_block, delete_col_ids);
1123
852
        RETURN_IF_ERROR(equality_delete_impl->init(_profile));
1124
852
        _equality_delete_impls.emplace_back(std::move(equality_delete_impl));
1125
852
    }
1126
670
    return Status::OK();
1127
670
}
1128
1129
Status IcebergOrcReader::_process_equality_delete(
1130
670
        const std::vector<TIcebergDeleteFileDesc>& delete_files) {
1131
670
    std::unordered_map<std::string, std::tuple<std::string, const SlotDescriptor*>>
1132
670
            partition_columns;
1133
670
    std::unordered_map<std::string, VExprContextSPtr> missing_columns;
1134
1135
670
    std::map<int, int> data_file_id_to_field_idx;
1136
2.67k
    for (int idx = 0; idx < _data_file_type_desc->getSubtypeCount(); ++idx) {
1137
2.00k
        if (!_data_file_type_desc->getSubtype(idx)->hasAttributeKey(ICEBERG_ORC_ATTRIBUTE)) {
1138
0
            return Status::DataQualityError("Iceberg equality delete data file missing field id.");
1139
0
        }
1140
2.00k
        auto field_id = std::stoi(
1141
2.00k
                _data_file_type_desc->getSubtype(idx)->getAttributeValue(ICEBERG_ORC_ATTRIBUTE));
1142
2.00k
        data_file_id_to_field_idx[field_id] = idx;
1143
2.00k
    }
1144
1145
1.52k
    for (const auto& delete_file : delete_files) {
1146
1.52k
        TFileRangeDesc delete_desc;
1147
        // must use __set() method to make sure __isset is true
1148
1.52k
        delete_desc.__set_fs_name(_range.fs_name);
1149
1.52k
        delete_desc.path = delete_file.path;
1150
1.52k
        delete_desc.start_offset = 0;
1151
1.52k
        delete_desc.size = -1;
1152
1.52k
        delete_desc.file_size = -1;
1153
1154
1.52k
        if (!delete_file.__isset.field_ids) [[unlikely]] {
1155
0
            return Status::InternalError(
1156
0
                    "missing delete field ids when reading equality delete file");
1157
0
        }
1158
1.52k
        auto& read_column_field_ids = delete_file.field_ids;
1159
1.52k
        std::set<int> read_column_field_ids_set;
1160
2.36k
        for (const auto& field_id : read_column_field_ids) {
1161
2.36k
            read_column_field_ids_set.insert(field_id);
1162
2.36k
            _equality_delete_col_ids.insert(field_id);
1163
2.36k
        }
1164
1165
1.52k
        auto delete_reader = OrcReader::create_unique(_profile, _state, _params, delete_desc,
1166
1.52k
                                                      READ_DELETE_FILE_BATCH_SIZE,
1167
1.52k
                                                      _state->timezone(), _io_ctx, _meta_cache);
1168
1.52k
        RETURN_IF_ERROR(delete_reader->init_schema_reader());
1169
        // delete file schema
1170
1.52k
        std::vector<std::string> delete_file_col_names;
1171
1.52k
        std::vector<DataTypePtr> delete_file_col_types;
1172
1.52k
        RETURN_IF_ERROR(
1173
1.52k
                delete_reader->get_parsed_schema(&delete_file_col_names, &delete_file_col_types));
1174
1175
        // the column that to read equality delete file.
1176
        // (delete file maybe have extra columns that don't need to read)
1177
1.52k
        std::vector<std::string> delete_col_names;
1178
1.52k
        std::vector<DataTypePtr> delete_col_types;
1179
1.52k
        std::vector<int> delete_col_ids;
1180
1.52k
        std::unordered_map<std::string, uint32_t> delete_col_name_to_block_idx;
1181
1182
1.52k
        const orc::Type* delete_field_desc = nullptr;
1183
1.52k
        RETURN_IF_ERROR(delete_reader->get_file_type(&delete_field_desc));
1184
1.52k
        DCHECK(delete_field_desc != nullptr);
1185
1186
1.52k
        auto eq_file_node = std::make_shared<TableSchemaChangeHelper::StructNode>();
1187
1188
3.89k
        for (size_t idx = 0; idx < delete_field_desc->getSubtypeCount(); idx++) {
1189
2.37k
            auto delete_file_field = delete_field_desc->getSubtype(idx);
1190
1191
2.37k
            if (!delete_file_field->hasAttributeKey(ICEBERG_ORC_ATTRIBUTE))
1192
0
                    [[unlikely]] { // missing delete_file_field id
1193
                // equality delete file must have delete_file_field id to match column.
1194
0
                return Status::DataQualityError(
1195
0
                        "missing delete_file_field id when reading equality delete file");
1196
2.37k
            } else {
1197
2.37k
                auto delete_field_id =
1198
2.37k
                        std::stoi(delete_file_field->getAttributeValue(ICEBERG_ORC_ATTRIBUTE));
1199
2.37k
                if (read_column_field_ids_set.contains(delete_field_id)) {
1200
                    // the column that need to read.
1201
2.36k
                    if (is_complex_type(delete_file_col_types[idx]->get_primitive_type()))
1202
0
                            [[unlikely]] {
1203
0
                        return Status::InternalError(
1204
0
                                "can not support read complex column in equality delete file.");
1205
2.36k
                    } else if (!data_file_id_to_field_idx.contains(delete_field_id)) [[unlikely]] {
1206
0
                        return Status::DataQualityError(
1207
0
                                "can not find delete field id in data file schema when reading "
1208
0
                                "equality delete file");
1209
0
                    }
1210
1211
2.36k
                    auto data_file_field = _data_file_type_desc->getSubtype(
1212
2.36k
                            data_file_id_to_field_idx[delete_field_id]);
1213
1214
2.36k
                    if (delete_file_field->getKind() != data_file_field->getKind()) [[unlikely]] {
1215
0
                        return Status::NotSupported(
1216
0
                                "Not Support type change in equality delete, field: {}, delete "
1217
0
                                "file type: {}, data file type: {}",
1218
0
                                delete_field_id, delete_file_field->getKind(),
1219
0
                                data_file_field->getKind());
1220
0
                    }
1221
2.36k
                    std::string filed_lower_name = to_lower(delete_field_desc->getFieldName(idx));
1222
2.36k
                    eq_file_node->add_children(
1223
2.36k
                            filed_lower_name, delete_field_desc->getFieldName(idx),
1224
2.36k
                            std::make_shared<TableSchemaChangeHelper::ScalarNode>());
1225
1226
2.36k
                    delete_col_ids.emplace_back(delete_field_id);
1227
2.36k
                    delete_col_names.emplace_back(filed_lower_name);
1228
2.36k
                    delete_col_types.emplace_back(make_nullable(delete_file_col_types[idx]));
1229
2.36k
                    read_column_field_ids_set.erase(delete_field_id);
1230
2.36k
                }
1231
2.37k
            }
1232
2.37k
        }
1233
1.52k
        if (!read_column_field_ids_set.empty()) [[unlikely]] {
1234
0
            return Status::DataQualityError("some field ids not found in equality delete file.");
1235
0
        }
1236
1237
3.88k
        for (uint32_t idx = 0; idx < delete_col_names.size(); ++idx) {
1238
2.36k
            delete_col_name_to_block_idx[delete_col_names[idx]] = idx;
1239
2.36k
        }
1240
1241
1.52k
        RETURN_IF_ERROR(delete_reader->init_reader(&delete_col_names, &delete_col_name_to_block_idx,
1242
1.52k
                                                   {}, false, nullptr, nullptr, nullptr, nullptr,
1243
1.52k
                                                   eq_file_node));
1244
1.52k
        RETURN_IF_ERROR(delete_reader->set_fill_columns(partition_columns, missing_columns));
1245
1246
1.52k
        if (!_equality_delete_block_map.contains(delete_col_ids)) {
1247
852
            _equality_delete_block_map.emplace(delete_col_ids, _equality_delete_blocks.size());
1248
852
            Block block;
1249
852
            _generate_equality_delete_block(&block, delete_col_names, delete_col_types);
1250
852
            _equality_delete_blocks.emplace_back(block);
1251
852
        }
1252
1.52k
        Block& eq_file_block = _equality_delete_blocks[_equality_delete_block_map[delete_col_ids]];
1253
1.52k
        bool eof = false;
1254
4.57k
        while (!eof) {
1255
3.04k
            Block tmp_block;
1256
3.04k
            _generate_equality_delete_block(&tmp_block, delete_col_names, delete_col_types);
1257
3.04k
            size_t read_rows = 0;
1258
3.04k
            RETURN_IF_ERROR(delete_reader->get_next_block(&tmp_block, &read_rows, &eof));
1259
3.04k
            if (read_rows > 0) {
1260
1.52k
                MutableBlock mutable_block(&eq_file_block);
1261
1.52k
                RETURN_IF_ERROR(mutable_block.merge(tmp_block));
1262
1.52k
            }
1263
3.04k
        }
1264
1.52k
    }
1265
1266
852
    for (const auto& [delete_col_ids, block_idx] : _equality_delete_block_map) {
1267
852
        auto& eq_file_block = _equality_delete_blocks[block_idx];
1268
852
        auto equality_delete_impl =
1269
852
                EqualityDeleteBase::get_delete_impl(&eq_file_block, delete_col_ids);
1270
852
        RETURN_IF_ERROR(equality_delete_impl->init(_profile));
1271
852
        _equality_delete_impls.emplace_back(std::move(equality_delete_impl));
1272
852
    }
1273
670
    return Status::OK();
1274
670
}
1275
#include "common/compile_check_end.h"
1276
} // namespace doris