Coverage Report

Created: 2026-07-10 14:51

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format_v2/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_v2/table/iceberg_reader.h"
19
20
#include <algorithm>
21
#include <memory>
22
#include <sstream>
23
#include <utility>
24
25
#include "common/cast_set.h"
26
#include "common/consts.h"
27
#include "core/assert_cast.h"
28
#include "core/block/block.h"
29
#include "core/column/column_const.h"
30
#include "core/column/column_nullable.h"
31
#include "core/column/column_string.h"
32
#include "core/column/column_struct.h"
33
#include "core/column/column_vector.h"
34
#include "core/data_type/data_type_number.h"
35
#include "core/data_type/define_primitive_type.h"
36
#include "core/field.h"
37
#include "exprs/vslot_ref.h"
38
#include "format/table/deletion_vector_reader.h"
39
#include "format_v2/expr/cast.h"
40
#include "format_v2/expr/equality_delete_predicate.h"
41
#include "format_v2/orc/orc_reader.h"
42
#include "format_v2/parquet/parquet_reader.h"
43
#include "format_v2/parquet/reader/column_reader.h"
44
#include "format_v2/table_reader.h"
45
#include "io/file_factory.h"
46
47
namespace doris::format::iceberg {
48
49
static constexpr const char* ROW_LINEAGE_ROW_ID = "_row_id";
50
static constexpr int32_t ROW_LINEAGE_ROW_ID_FIELD_ID = 2147483540;
51
52
template <typename T>
53
0
static std::string join_values_for_debug(const std::vector<T>& values) {
54
0
    std::ostringstream out;
55
0
    out << "[";
56
0
    for (size_t idx = 0; idx < values.size(); ++idx) {
57
0
        if (idx > 0) {
58
0
            out << ", ";
59
0
        }
60
0
        out << values[idx];
61
0
    }
62
0
    out << "]";
63
0
    return out.str();
64
0
}
65
66
1
static bool is_projected_row_lineage_row_id(const format::ColumnDefinition& column) {
67
    // Iceberg row lineage columns can be bound by field id when a mapper has already been built,
68
    // but customize_file_scan_request() is also exercised directly by scan-request tests before the
69
    // mapper exists. In that path, inspect the projected table schema so row-position dependencies
70
    // are still added for `_row_id`.
71
1
    return column.name == ROW_LINEAGE_ROW_ID ||
72
1
           (column.has_identifier_field_id() &&
73
0
            column.get_identifier_field_id() == ROW_LINEAGE_ROW_ID_FIELD_ID);
74
1
}
75
76
16
static bool is_projected_iceberg_rowid(const format::ColumnDefinition& column) {
77
16
    return column.name == BeConsts::ICEBERG_ROWID_COL;
78
16
}
79
80
0
static std::string iceberg_delete_file_debug_string(const TIcebergDeleteFileDesc& delete_file) {
81
0
    std::ostringstream out;
82
0
    out << "TIcebergDeleteFileDesc{path=" << (delete_file.__isset.path ? delete_file.path : "null")
83
0
        << ", content=" << (delete_file.__isset.content ? delete_file.content : -1)
84
0
        << ", file_format="
85
0
        << (delete_file.__isset.file_format ? static_cast<int>(delete_file.file_format) : -1)
86
0
        << ", position_lower_bound="
87
0
        << (delete_file.__isset.position_lower_bound ? delete_file.position_lower_bound : -1)
88
0
        << ", position_upper_bound="
89
0
        << (delete_file.__isset.position_upper_bound ? delete_file.position_upper_bound : -1)
90
0
        << ", field_ids="
91
0
        << (delete_file.__isset.field_ids ? join_values_for_debug(delete_file.field_ids) : "[]")
92
0
        << ", content_offset="
93
0
        << (delete_file.__isset.content_offset ? delete_file.content_offset : -1)
94
0
        << ", content_size_in_bytes="
95
0
        << (delete_file.__isset.content_size_in_bytes ? delete_file.content_size_in_bytes : -1)
96
0
        << "}";
97
0
    return out.str();
98
0
}
99
100
static std::string iceberg_delete_files_debug_string(
101
0
        const std::vector<TIcebergDeleteFileDesc>& delete_files) {
102
0
    std::ostringstream out;
103
0
    out << "[";
104
0
    for (size_t idx = 0; idx < delete_files.size(); ++idx) {
105
0
        if (idx > 0) {
106
0
            out << ", ";
107
0
        }
108
0
        out << iceberg_delete_file_debug_string(delete_files[idx]);
109
0
    }
110
0
    out << "]";
111
0
    return out.str();
112
0
}
113
114
0
static std::string iceberg_params_debug_string(const std::optional<TIcebergFileDesc>& params) {
115
0
    if (!params.has_value()) {
116
0
        return "null";
117
0
    }
118
0
    const auto& iceberg_params = *params;
119
0
    std::ostringstream out;
120
0
    out << "TIcebergFileDesc{format_version="
121
0
        << (iceberg_params.__isset.format_version ? iceberg_params.format_version : -1)
122
0
        << ", content=" << (iceberg_params.__isset.content ? iceberg_params.content : -1)
123
0
        << ", original_file_path="
124
0
        << (iceberg_params.__isset.original_file_path ? iceberg_params.original_file_path : "null")
125
0
        << ", row_count=" << (iceberg_params.__isset.row_count ? iceberg_params.row_count : -1)
126
0
        << ", partition_spec_id="
127
0
        << (iceberg_params.__isset.partition_spec_id ? iceberg_params.partition_spec_id : 0)
128
0
        << ", has_partition_data_json=" << iceberg_params.__isset.partition_data_json
129
0
        << ", first_row_id="
130
0
        << (iceberg_params.__isset.first_row_id ? iceberg_params.first_row_id : -1)
131
0
        << ", last_updated_sequence_number="
132
0
        << (iceberg_params.__isset.last_updated_sequence_number
133
0
                    ? iceberg_params.last_updated_sequence_number
134
0
                    : -1)
135
0
        << ", delete_file_count="
136
0
        << (iceberg_params.__isset.delete_files ? iceberg_params.delete_files.size() : 0)
137
0
        << ", delete_files="
138
0
        << (iceberg_params.__isset.delete_files
139
0
                    ? iceberg_delete_files_debug_string(iceberg_params.delete_files)
140
0
                    : "[]")
141
0
        << ", has_serialized_split=" << iceberg_params.__isset.serialized_split << "}";
142
0
    return out.str();
143
0
}
144
145
IcebergTableReader::PositionDeleteRowsCollector::PositionDeleteRowsCollector(
146
        std::string data_file_path, format::DeleteRows* rows)
147
8
        : _data_file_path(std::move(data_file_path)), _rows(rows) {}
148
149
Status IcebergTableReader::PositionDeleteRowsCollector::collect(const Block& block,
150
14
                                                                size_t read_rows) {
151
14
    if (read_rows == 0) {
152
6
        return Status::OK();
153
6
    }
154
8
    const auto& file_path_column_ptr =
155
8
            block.get_by_position(ICEBERG_FILE_PATH_BLOCK_POSITION).column;
156
8
    const auto& pos_column_ptr = block.get_by_position(ICEBERG_ROW_POS_BLOCK_POSITION).column;
157
8
    if (const auto* nullable_column = check_and_get_column<ColumnNullable>(*file_path_column_ptr);
158
8
        nullable_column != nullptr && nullable_column->has_null(0, read_rows)) {
159
1
        return Status::Corruption("Iceberg position delete column file_path contains null values");
160
1
    }
161
7
    if (const auto* nullable_column = check_and_get_column<ColumnNullable>(*pos_column_ptr);
162
7
        nullable_column != nullptr && nullable_column->has_null(0, read_rows)) {
163
1
        return Status::Corruption("Iceberg position delete column pos contains null values");
164
1
    }
165
6
    const auto& file_path_column =
166
6
            assert_cast<const ColumnString&>(*remove_nullable(file_path_column_ptr));
167
6
    const auto& pos_column = assert_cast<const ColumnInt64&>(*remove_nullable(pos_column_ptr));
168
15
    for (size_t row = 0; row < read_rows; ++row) {
169
9
        const auto file_path = file_path_column.get_data_at(row).to_string();
170
9
        if (file_path == _data_file_path) {
171
8
            _rows->push_back(pos_column.get_element(row));
172
8
        }
173
9
    }
174
6
    return Status::OK();
175
7
}
176
177
27
Status IcebergTableReader::prepare_split(const format::SplitReadOptions& options) {
178
27
    _row_lineage_columns = {};
179
27
    _iceberg_params.reset();
180
27
    _delete_predicates_initialized = false;
181
27
    _position_delete_rows_storage.clear();
182
27
    _equality_delete_filters.clear();
183
27
    if (options.current_range.__isset.table_format_params &&
184
27
        options.current_range.table_format_params.__isset.iceberg_params) {
185
25
        const auto& iceberg_params = options.current_range.table_format_params.iceberg_params;
186
25
        _iceberg_params = iceberg_params;
187
25
        if (iceberg_params.__isset.first_row_id) {
188
8
            _row_lineage_columns.first_row_id = iceberg_params.first_row_id;
189
8
        }
190
25
        if (iceberg_params.__isset.last_updated_sequence_number) {
191
6
            _row_lineage_columns.last_updated_sequence_number =
192
6
                    iceberg_params.last_updated_sequence_number;
193
6
        }
194
25
    }
195
27
    RETURN_IF_ERROR(TableReader::prepare_split(options));
196
24
    if (_is_table_level_count_active()) {
197
1
        return Status::OK();
198
1
    }
199
23
    RETURN_IF_ERROR(_init_delete_predicates(options.current_range.table_format_params));
200
21
    return Status::OK();
201
23
}
202
203
0
std::string IcebergTableReader::debug_string() const {
204
0
    size_t position_delete_file_count = 0;
205
0
    size_t equality_delete_file_count = 0;
206
0
    size_t deletion_vector_file_count = 0;
207
0
    if (_iceberg_params.has_value() && _iceberg_params->__isset.delete_files) {
208
0
        for (const auto& delete_file : _iceberg_params->delete_files) {
209
0
            if (!delete_file.__isset.content) {
210
0
                continue;
211
0
            }
212
0
            if (delete_file.content == POSITION_DELETE) {
213
0
                ++position_delete_file_count;
214
0
            } else if (delete_file.content == EQUALITY_DELETE) {
215
0
                ++equality_delete_file_count;
216
0
            } else if (delete_file.content == DELETION_VECTOR) {
217
0
                ++deletion_vector_file_count;
218
0
            }
219
0
        }
220
0
    }
221
222
0
    std::ostringstream equality_filters;
223
0
    equality_filters << "[";
224
0
    for (size_t idx = 0; idx < _equality_delete_filters.size(); ++idx) {
225
0
        if (idx > 0) {
226
0
            equality_filters << ", ";
227
0
        }
228
0
        const auto& filter = _equality_delete_filters[idx];
229
0
        equality_filters << "EqualityDeleteFilter{field_ids="
230
0
                         << join_values_for_debug(filter.field_ids) << ", key_types=[";
231
0
        for (size_t type_idx = 0; type_idx < filter.key_types.size(); ++type_idx) {
232
0
            if (type_idx > 0) {
233
0
                equality_filters << ", ";
234
0
            }
235
0
            equality_filters << (filter.key_types[type_idx] == nullptr
236
0
                                         ? "null"
237
0
                                         : filter.key_types[type_idx]->get_name());
238
0
        }
239
0
        equality_filters << "], delete_block_rows=" << filter.delete_block.rows()
240
0
                         << ", delete_block_columns=" << filter.delete_block.columns() << "}";
241
0
    }
242
0
    equality_filters << "]";
243
244
0
    std::ostringstream out;
245
0
    out << "IcebergTableReader{base=" << format::TableReader::debug_string()
246
0
        << ", iceberg_params=" << iceberg_params_debug_string(_iceberg_params)
247
0
        << ", row_lineage_first_row_id=" << _row_lineage_columns.first_row_id
248
0
        << ", row_lineage_last_updated_sequence_number="
249
0
        << _row_lineage_columns.last_updated_sequence_number
250
0
        << ", need_row_lineage_row_id=" << _need_row_lineage_row_id()
251
0
        << ", need_iceberg_rowid=" << _need_iceberg_rowid()
252
0
        << ", row_position_block_position=" << _row_position_block_position
253
0
        << ", delete_predicates_initialized=" << _delete_predicates_initialized
254
0
        << ", position_delete_file_count=" << position_delete_file_count
255
0
        << ", equality_delete_file_count=" << equality_delete_file_count
256
0
        << ", deletion_vector_file_count=" << deletion_vector_file_count
257
0
        << ", position_delete_rows_storage_count=" << _position_delete_rows_storage.size()
258
0
        << ", equality_delete_filter_count=" << _equality_delete_filters.size()
259
0
        << ", equality_delete_filters=" << equality_filters.str() << "}";
260
0
    return out.str();
261
0
}
262
263
20
Status IcebergTableReader::materialize_virtual_columns(Block* table_block) {
264
58
    for (size_t column_idx = 0; column_idx < _data_reader.column_mapper->mappings().size();
265
38
         ++column_idx) {
266
38
        const auto& mapping = _data_reader.column_mapper->mappings()[column_idx];
267
38
        switch (mapping.virtual_column_type) {
268
9
        case format::TableVirtualColumnType::ROW_ID:
269
9
            RETURN_IF_ERROR(_materialize_row_lineage_row_id(table_block, column_idx));
270
9
            break;
271
9
        case format::TableVirtualColumnType::LAST_UPDATED_SEQUENCE_NUMBER:
272
8
            RETURN_IF_ERROR(
273
8
                    _materialize_row_lineage_last_updated_sequence_number(table_block, column_idx));
274
8
            break;
275
8
        case format::TableVirtualColumnType::ICEBERG_ROWID:
276
1
            RETURN_IF_ERROR(_materialize_iceberg_rowid(table_block, column_idx));
277
1
            break;
278
20
        case format::TableVirtualColumnType::INVALID:
279
20
            break;
280
38
        }
281
38
    }
282
20
    return Status::OK();
283
20
}
284
285
21
Status IcebergTableReader::customize_file_scan_request(format::FileScanRequest* file_request) {
286
21
    RETURN_IF_ERROR(TableReader::customize_file_scan_request(file_request));
287
21
    if ((_row_lineage_columns.first_row_id >= 0 && _need_row_lineage_row_id()) ||
288
21
        _need_iceberg_rowid()) {
289
9
        RETURN_IF_ERROR(_append_row_position_output_column(file_request));
290
9
    }
291
21
    RETURN_IF_ERROR(_append_equality_delete_predicates(file_request));
292
21
    return Status::OK();
293
21
}
294
295
20
bool IcebergTableReader::_supports_aggregate_pushdown(TPushAggOp::type agg_type) const {
296
20
    if (!TableReader::_supports_aggregate_pushdown(agg_type)) {
297
19
        return false;
298
19
    }
299
1
    return _equality_delete_filters.empty();
300
20
}
301
302
Status IcebergTableReader::_parse_deletion_vector_file(const TTableFormatFileDesc& t_desc,
303
                                                       DeleteFileDesc* desc,
304
33
                                                       bool* has_delete_file) {
305
33
    DORIS_CHECK(desc != nullptr);
306
33
    DORIS_CHECK(has_delete_file != nullptr);
307
33
    *has_delete_file = false;
308
33
    if (!t_desc.__isset.iceberg_params) {
309
2
        return Status::OK();
310
2
    }
311
31
    const auto& iceberg_params = t_desc.iceberg_params;
312
31
    if (!iceberg_params.__isset.format_version ||
313
31
        iceberg_params.format_version < MIN_SUPPORT_DELETE_FILES_VERSION ||
314
31
        !iceberg_params.__isset.delete_files || iceberg_params.delete_files.empty()) {
315
8
        return Status::OK();
316
8
    }
317
318
23
    const TIcebergDeleteFileDesc* deletion_vector = nullptr;
319
25
    for (const auto& delete_file : iceberg_params.delete_files) {
320
25
        if (!delete_file.__isset.content || delete_file.content != DELETION_VECTOR) {
321
11
            continue;
322
11
        }
323
14
        if (deletion_vector != nullptr) {
324
1
            return Status::DataQualityError("This iceberg data file has multiple DVs.");
325
1
        }
326
13
        deletion_vector = &delete_file;
327
13
    }
328
22
    if (deletion_vector == nullptr) {
329
10
        return Status::OK();
330
10
    }
331
12
    if (!deletion_vector->__isset.content_offset ||
332
12
        !deletion_vector->__isset.content_size_in_bytes) {
333
1
        return Status::InternalError("Deletion vector is missing content offset or length");
334
1
    }
335
336
11
    const std::string data_file_path = iceberg_params.__isset.original_file_path
337
11
                                               ? iceberg_params.original_file_path
338
11
                                               : _data_file_path();
339
11
    desc->key = build_iceberg_deletion_vector_cache_key(data_file_path, *deletion_vector);
340
11
    desc->path = deletion_vector->path;
341
11
    desc->start_offset = deletion_vector->content_offset;
342
11
    desc->size = deletion_vector->content_size_in_bytes;
343
11
    desc->file_size = -1;
344
11
    desc->format = DeleteFileDesc::Format::ICEBERG;
345
11
    *has_delete_file = true;
346
11
    return Status::OK();
347
12
}
348
349
23
Status IcebergTableReader::_init_delete_predicates(const TTableFormatFileDesc& t_desc) {
350
23
    if (!t_desc.__isset.iceberg_params || _delete_predicates_initialized) {
351
2
        _delete_predicates_initialized = true;
352
2
        return Status::OK();
353
2
    }
354
21
    const auto& iceberg_params = t_desc.iceberg_params;
355
21
    if (!iceberg_params.__isset.format_version ||
356
21
        iceberg_params.format_version < MIN_SUPPORT_DELETE_FILES_VERSION ||
357
21
        !iceberg_params.__isset.delete_files || iceberg_params.delete_files.empty()) {
358
8
        _delete_predicates_initialized = true;
359
8
        return Status::OK();
360
8
    }
361
362
13
    std::vector<TIcebergDeleteFileDesc> position_delete_files;
363
13
    std::vector<TIcebergDeleteFileDesc> equality_delete_files;
364
14
    for (const auto& delete_file : iceberg_params.delete_files) {
365
14
        if (!delete_file.__isset.content) {
366
0
            continue;
367
0
        }
368
14
        if (delete_file.content == POSITION_DELETE) {
369
9
            position_delete_files.push_back(delete_file);
370
9
        } else if (delete_file.content == EQUALITY_DELETE) {
371
2
            equality_delete_files.push_back(delete_file);
372
2
        }
373
14
    }
374
    // `_delete_rows != nullptr` means a deletion vector is parsed. Per Iceberg scan planning,
375
    // position delete files apply only when there is no deletion vector for the data file.
376
13
    if (_delete_rows != nullptr) {
377
3
        _position_delete_rows_storage = *_delete_rows;
378
3
        _delete_rows = &_position_delete_rows_storage;
379
3
        position_delete_files.clear();
380
3
    }
381
    // Initialize position and equality delete predicates. Position delete files contain row
382
    // positions of deleted rows, which can be directly added to `_delete_rows`. Equality delete
383
    // files contain values of deleted rows, which require reading the files and building
384
    // predicates for later filtering.
385
13
    if (!position_delete_files.empty()) {
386
8
        RETURN_IF_ERROR(_init_position_delete_rows(position_delete_files));
387
8
    }
388
11
    if (!equality_delete_files.empty()) {
389
2
        RETURN_IF_ERROR(_init_equality_delete_predicates(equality_delete_files));
390
2
    }
391
392
11
    _delete_predicates_initialized = true;
393
11
    return Status::OK();
394
11
}
395
396
std::shared_ptr<io::FileSystemProperties> IcebergTableReader::_delete_file_system_properties(
397
10
        const TFileScanRangeParams& scan_params) {
398
10
    auto system_properties = std::make_shared<io::FileSystemProperties>();
399
10
    system_properties->system_type =
400
10
            scan_params.__isset.file_type ? scan_params.file_type : TFileType::FILE_LOCAL;
401
10
    system_properties->properties = scan_params.properties;
402
10
    system_properties->hdfs_params = scan_params.hdfs_params;
403
10
    if (scan_params.__isset.broker_addresses) {
404
0
        system_properties->broker_addresses.assign(scan_params.broker_addresses.begin(),
405
0
                                                   scan_params.broker_addresses.end());
406
0
    }
407
10
    return system_properties;
408
10
}
409
410
std::unique_ptr<io::FileDescription> IcebergTableReader::_delete_file_description(
411
10
        const TFileRangeDesc& range) {
412
10
    auto file_description = std::make_unique<io::FileDescription>();
413
10
    file_description->path = range.path;
414
10
    file_description->file_size = range.__isset.file_size ? range.file_size : -1;
415
10
    file_description->range_start_offset = range.__isset.start_offset ? range.start_offset : 0;
416
10
    file_description->range_size = range.__isset.size ? range.size : -1;
417
10
    if (range.__isset.fs_name) {
418
0
        file_description->fs_name = range.fs_name;
419
0
    }
420
10
    return file_description;
421
10
}
422
423
9
std::string IcebergTableReader::_data_file_path() const {
424
9
    if (_iceberg_params.has_value() && _iceberg_params->__isset.original_file_path) {
425
8
        return _iceberg_params->original_file_path;
426
8
    }
427
1
    DORIS_CHECK(_current_task != nullptr);
428
1
    DORIS_CHECK(_current_task->data_file != nullptr);
429
1
    return _current_task->data_file->path;
430
9
}
431
432
9
Status IcebergTableReader::_append_row_position_output_column(format::FileScanRequest* request) {
433
9
    const auto row_position_column_id = format::LocalColumnId(format::ROW_POSITION_COLUMN_ID);
434
9
    _append_file_scan_column(request, row_position_column_id, &request->non_predicate_columns);
435
9
    _row_position_block_position = request->local_positions.at(row_position_column_id).value();
436
9
    return Status::OK();
437
9
}
438
439
21
Status IcebergTableReader::_append_equality_delete_predicates(format::FileScanRequest* request) {
440
21
    DORIS_CHECK(request != nullptr);
441
21
    for (const auto& filter : _equality_delete_filters) {
442
2
        auto delete_predicate =
443
2
                std::make_shared<EqualityDeletePredicate>(filter.delete_block, filter.field_ids);
444
2
        DCHECK_EQ(filter.field_ids.size(), filter.key_types.size());
445
4
        for (size_t idx = 0; idx < filter.field_ids.size(); ++idx) {
446
2
            const int field_id = filter.field_ids[idx];
447
2
            auto field_it = std::ranges::find_if(
448
2
                    _data_reader.file_schema, [field_id](const format::ColumnDefinition& field) {
449
2
                        return field.has_identifier_field_id() &&
450
2
                               field.get_identifier_field_id() == field_id;
451
2
                    });
452
2
            if (field_it == _data_reader.file_schema.end()) {
453
0
                return Status::InternalError(
454
0
                        "Can not find equality delete column field id {} in data file schema",
455
0
                        field_id);
456
0
            }
457
2
            const auto field_column_id = format::LocalColumnId(field_it->file_local_id());
458
2
            _append_file_scan_column(request, field_column_id, &request->predicate_columns);
459
2
            const auto block_position = request->local_positions.at(field_column_id).value();
460
2
            auto slot = VSlotRef::create_shared(cast_set<int>(block_position),
461
2
                                                cast_set<int>(block_position), -1, field_it->type,
462
2
                                                field_it->name);
463
2
            if (field_it->type->equals(*filter.key_types[idx])) {
464
1
                delete_predicate->add_child(std::move(slot));
465
1
            } else {
466
1
                auto cast_expr = Cast::create_shared(filter.key_types[idx]);
467
1
                cast_expr->add_child(std::move(slot));
468
1
                delete_predicate->add_child(std::move(cast_expr));
469
1
            }
470
2
        }
471
2
        request->delete_conjuncts.push_back(
472
2
                VExprContext::create_shared(std::move(delete_predicate)));
473
2
    }
474
21
    return Status::OK();
475
21
}
476
477
Status IcebergTableReader::_create_delete_file_reader(const TIcebergDeleteFileDesc& delete_file,
478
                                                      const TFileScanRangeParams& scan_params,
479
                                                      IcebergDeleteFileIOContext* delete_io_ctx,
480
10
                                                      std::unique_ptr<format::FileReader>* reader) {
481
10
    DORIS_CHECK(delete_io_ctx != nullptr);
482
10
    DORIS_CHECK(reader != nullptr);
483
10
    if (!delete_file.__isset.file_format) {
484
0
        return Status::InternalError("Iceberg delete file is missing file format");
485
0
    }
486
10
    if (delete_file.file_format != TFileFormatType::FORMAT_PARQUET &&
487
10
        delete_file.file_format != TFileFormatType::FORMAT_ORC) {
488
0
        return Status::NotSupported("Unsupported Iceberg delete file format {}",
489
0
                                    delete_file.file_format);
490
0
    }
491
10
    auto delete_range = build_iceberg_delete_file_range(delete_file.path);
492
10
    if (_current_task != nullptr && _current_task->data_file != nullptr &&
493
10
        !_current_task->data_file->fs_name.empty()) {
494
0
        delete_range.__set_fs_name(_current_task->data_file->fs_name);
495
0
    }
496
10
    auto system_properties = _delete_file_system_properties(scan_params);
497
10
    auto file_description = _delete_file_description(delete_range);
498
10
    std::shared_ptr<io::IOContext> io_ctx(&delete_io_ctx->io_ctx, [](io::IOContext*) {});
499
10
    if (delete_file.file_format == TFileFormatType::FORMAT_PARQUET) {
500
10
        *reader = std::make_unique<format::parquet::ParquetReader>(
501
10
                system_properties, file_description, io_ctx, _scanner_profile);
502
10
    } else {
503
0
        *reader = std::make_unique<format::orc::OrcReader>(system_properties, file_description,
504
0
                                                           io_ctx, _scanner_profile);
505
0
    }
506
10
    RETURN_IF_ERROR((*reader)->init(_runtime_state));
507
10
    return Status::OK();
508
10
}
509
510
Status IcebergTableReader::_read_position_delete_file(const TIcebergDeleteFileDesc& delete_file,
511
                                                      const TFileScanRangeParams& scan_params,
512
                                                      IcebergDeleteFileIOContext* delete_io_ctx,
513
8
                                                      PositionDeleteRowsCollector* collector) {
514
8
    DORIS_CHECK(collector != nullptr);
515
8
    std::unique_ptr<format::FileReader> reader;
516
8
    RETURN_IF_ERROR(_create_delete_file_reader(delete_file, scan_params, delete_io_ctx, &reader));
517
8
    DORIS_CHECK(reader != nullptr);
518
519
8
    std::vector<format::ColumnDefinition> schema;
520
8
    RETURN_IF_ERROR(reader->get_schema(&schema));
521
8
    format::ColumnDefinition* file_path_field = nullptr;
522
8
    format::ColumnDefinition* pos_field = nullptr;
523
16
    for (auto& field : schema) {
524
16
        if (field.name == ICEBERG_FILE_PATH) {
525
8
            file_path_field = &field;
526
8
        } else if (field.name == ICEBERG_ROW_POS) {
527
8
            pos_field = &field;
528
8
        }
529
16
    }
530
8
    if (file_path_field == nullptr || pos_field == nullptr) {
531
0
        return Status::InternalError("Position delete file is missing required columns");
532
0
    }
533
534
8
    auto request = std::make_shared<format::FileScanRequest>();
535
8
    request->non_predicate_columns = {
536
8
            format::LocalColumnIndex::top_level(
537
8
                    format::LocalColumnId(file_path_field->file_local_id())),
538
8
            format::LocalColumnIndex::top_level(format::LocalColumnId(pos_field->file_local_id()))};
539
8
    request->local_positions = {
540
8
            {format::LocalColumnId(file_path_field->file_local_id()),
541
8
             format::LocalIndex(ICEBERG_FILE_PATH_BLOCK_POSITION)},
542
8
            {format::LocalColumnId(pos_field->file_local_id()),
543
8
             format::LocalIndex(ICEBERG_ROW_POS_BLOCK_POSITION)},
544
8
    };
545
8
    RETURN_IF_ERROR(reader->open(request));
546
547
8
    bool eof = false;
548
8
    auto build_position_delete_block = [](const format::ColumnDefinition& file_path_field,
549
14
                                          const format::ColumnDefinition& pos_field) -> Block {
550
14
        Block block;
551
14
        block.insert(
552
14
                {file_path_field.type->create_column(), file_path_field.type, ICEBERG_FILE_PATH});
553
14
        block.insert({pos_field.type->create_column(), pos_field.type, ICEBERG_ROW_POS});
554
14
        return block;
555
14
    };
556
20
    while (!eof) {
557
14
        Block block = build_position_delete_block(*file_path_field, *pos_field);
558
14
        size_t read_rows = 0;
559
14
        RETURN_IF_ERROR(reader->get_block(&block, &read_rows, &eof));
560
14
        RETURN_IF_ERROR(collector->collect(block, read_rows));
561
14
    }
562
6
    return reader->close();
563
8
}
564
565
Status IcebergTableReader::_init_position_delete_rows(
566
8
        const std::vector<TIcebergDeleteFileDesc>& delete_files) {
567
8
    TFileScanRangeParams delete_scan_params =
568
8
            _scan_params == nullptr ? TFileScanRangeParams() : *_scan_params;
569
8
    format::DeleteRows position_delete_rows;
570
8
    IcebergDeleteFileIOContext delete_io_ctx(_runtime_state);
571
8
    PositionDeleteRowsCollector collector(_data_file_path(), &position_delete_rows);
572
8
    for (const auto& delete_file : delete_files) {
573
8
        RETURN_IF_ERROR(_read_position_delete_file(delete_file, delete_scan_params, &delete_io_ctx,
574
8
                                                   &collector));
575
8
    }
576
6
    if (position_delete_rows.empty()) {
577
0
        return Status::OK();
578
0
    }
579
    // Position delete files and deletion vectors both become row-position deletes for the
580
    // common TableReader DeletePredicate path. Keep the merged rows in a member vector because
581
    // DeletePredicate stores a reference to the vector used by _delete_rows.
582
6
    _position_delete_rows_storage.insert(_position_delete_rows_storage.end(),
583
6
                                         position_delete_rows.begin(), position_delete_rows.end());
584
6
    std::sort(_position_delete_rows_storage.begin(), _position_delete_rows_storage.end());
585
6
    _position_delete_rows_storage.erase(
586
6
            std::unique(_position_delete_rows_storage.begin(), _position_delete_rows_storage.end()),
587
6
            _position_delete_rows_storage.end());
588
6
    _delete_rows = &_position_delete_rows_storage;
589
6
    return Status::OK();
590
6
}
591
592
Status IcebergTableReader::_init_equality_delete_predicates(
593
2
        const std::vector<TIcebergDeleteFileDesc>& delete_files) {
594
2
    TFileScanRangeParams delete_scan_params =
595
2
            _scan_params == nullptr ? TFileScanRangeParams() : *_scan_params;
596
2
    IcebergDeleteFileIOContext delete_io_ctx(_runtime_state);
597
2
    for (const auto& delete_file : delete_files) {
598
2
        RETURN_IF_ERROR(
599
2
                _read_equality_delete_file(delete_file, delete_scan_params, &delete_io_ctx));
600
2
    }
601
2
    return Status::OK();
602
2
}
603
604
Status IcebergTableReader::_read_equality_delete_file(const TIcebergDeleteFileDesc& delete_file,
605
                                                      const TFileScanRangeParams& scan_params,
606
2
                                                      IcebergDeleteFileIOContext* delete_io_ctx) {
607
2
    if (!delete_file.__isset.field_ids || delete_file.field_ids.empty()) {
608
0
        return Status::InternalError("Iceberg equality delete file is missing field ids");
609
0
    }
610
2
    std::unique_ptr<format::FileReader> reader;
611
2
    RETURN_IF_ERROR(_create_delete_file_reader(delete_file, scan_params, delete_io_ctx, &reader));
612
2
    DORIS_CHECK(reader != nullptr);
613
614
2
    std::vector<format::ColumnDefinition> schema;
615
2
    RETURN_IF_ERROR(reader->get_schema(&schema));
616
2
    std::vector<format::ColumnDefinition> delete_fields;
617
2
    std::vector<int> delete_field_ids;
618
2
    std::vector<DataTypePtr> delete_key_types;
619
2
    for (const auto field_id : delete_file.field_ids) {
620
2
        auto field_it = std::find_if(schema.begin(), schema.end(),
621
2
                                     [field_id](const format::ColumnDefinition& field) {
622
2
                                         return field.has_identifier_field_id() &&
623
2
                                                field_id == field.get_identifier_field_id();
624
2
                                     });
625
2
        if (field_it == schema.end()) {
626
0
            return Status::InternalError("Can not find field id {} in equality delete file {}",
627
0
                                         field_id, delete_file.path);
628
0
        }
629
2
        if (!field_it->children.empty()) {
630
0
            return Status::NotSupported(
631
0
                    "Iceberg equality delete does not support complex column {}", field_it->name);
632
0
        }
633
2
        delete_fields.push_back(*field_it);
634
2
        delete_field_ids.push_back(field_id);
635
2
        delete_key_types.push_back(field_it->type);
636
2
    }
637
638
2
    auto request = std::make_shared<format::FileScanRequest>();
639
4
    for (size_t idx = 0; idx < delete_fields.size(); ++idx) {
640
2
        const auto local_column_id = format::LocalColumnId(delete_fields[idx].file_local_id());
641
2
        request->non_predicate_columns.push_back(
642
2
                format::LocalColumnIndex::top_level(local_column_id));
643
2
        request->local_positions.emplace(local_column_id, format::LocalIndex(idx));
644
2
    }
645
2
    RETURN_IF_ERROR(reader->open(request));
646
647
2
    auto build_equality_delete_block =
648
6
            [](const std::vector<format::ColumnDefinition> fields) -> Block {
649
6
        Block block;
650
6
        for (const auto& field : fields) {
651
6
            block.insert({field.type->create_column(), field.type, field.name});
652
6
        }
653
6
        return block;
654
6
    };
655
2
    Block delete_block = build_equality_delete_block(delete_fields);
656
2
    MutableBlock mutable_delete_block(std::move(delete_block));
657
2
    bool eof = false;
658
6
    while (!eof) {
659
4
        Block block = build_equality_delete_block(delete_fields);
660
4
        size_t read_rows = 0;
661
4
        RETURN_IF_ERROR(reader->get_block(&block, &read_rows, &eof));
662
4
        if (read_rows > 0) {
663
2
            RETURN_IF_ERROR(mutable_delete_block.merge(block));
664
2
        }
665
4
    }
666
2
    RETURN_IF_ERROR(reader->close());
667
2
    delete_block = mutable_delete_block.to_block();
668
2
    _equality_delete_filters.push_back(
669
2
            EqualityDeleteFilter {.field_ids = std::move(delete_field_ids),
670
2
                                  .key_types = std::move(delete_key_types),
671
2
                                  .delete_block = std::move(delete_block)});
672
2
    return Status::OK();
673
2
}
674
675
9
Status IcebergTableReader::_materialize_row_lineage_row_id(Block* table_block, size_t column_idx) {
676
9
    if (_row_lineage_columns.first_row_id < 0) {
677
2
        return Status::OK();
678
2
    }
679
7
    DORIS_CHECK(_row_position_block_position < _data_reader.block_template.columns());
680
7
    const auto& row_position_column = assert_cast<const ColumnInt64&>(
681
7
            *_data_reader.block_template.get_by_position(_row_position_block_position).column);
682
7
    DORIS_CHECK(row_position_column.size() == table_block->rows());
683
7
    auto column = IColumn::mutate(
684
7
            table_block->get_by_position(column_idx).column->convert_to_full_column_if_const());
685
7
    auto* nullable_column = assert_cast<ColumnNullable*>(column.get());
686
7
    auto& null_map = nullable_column->get_null_map_data();
687
7
    auto& data = assert_cast<ColumnInt64&>(*nullable_column->get_nested_column_ptr()).get_data();
688
7
    DORIS_CHECK(null_map.size() == row_position_column.size());
689
7
    DORIS_CHECK(data.size() == row_position_column.size());
690
23
    for (size_t row = 0; row < row_position_column.size(); ++row) {
691
16
        if (null_map[row]) {
692
10
            null_map[row] = 0;
693
10
            data[row] = _row_lineage_columns.first_row_id + row_position_column.get_element(row);
694
10
        }
695
16
    }
696
7
    table_block->replace_by_position(column_idx, std::move(column));
697
7
    return Status::OK();
698
9
}
699
700
1
Status IcebergTableReader::_materialize_iceberg_rowid(Block* table_block, size_t column_idx) {
701
1
    DORIS_CHECK(_row_position_block_position < _data_reader.block_template.columns());
702
1
    const auto& row_position_column = assert_cast<const ColumnInt64&>(
703
1
            *_data_reader.block_template.get_by_position(_row_position_block_position).column);
704
1
    DORIS_CHECK(row_position_column.size() == table_block->rows());
705
706
1
    const auto& type = table_block->get_by_position(column_idx).type;
707
1
    auto column = type->create_column();
708
1
    auto* nullable_column = check_and_get_column<ColumnNullable>(column.get());
709
1
    auto* struct_column = nullable_column != nullptr
710
1
                                  ? check_and_get_column<ColumnStruct>(
711
1
                                            nullable_column->get_nested_column_ptr().get())
712
1
                                  : check_and_get_column<ColumnStruct>(column.get());
713
1
    DORIS_CHECK(struct_column != nullptr);
714
1
    DORIS_CHECK(struct_column->tuple_size() >= 4);
715
716
1
    const auto rows = row_position_column.size();
717
1
    const auto file_path = _data_file_path();
718
1
    const int32_t partition_spec_id =
719
1
            _iceberg_params.has_value() && _iceberg_params->__isset.partition_spec_id
720
1
                    ? _iceberg_params->partition_spec_id
721
1
                    : 0;
722
1
    const std::string partition_data_json =
723
1
            _iceberg_params.has_value() && _iceberg_params->__isset.partition_data_json
724
1
                    ? _iceberg_params->partition_data_json
725
1
                    : "";
726
727
1
    auto& file_path_column = struct_column->get_column(0);
728
1
    auto& row_pos_column = struct_column->get_column(1);
729
1
    auto& spec_id_column = struct_column->get_column(2);
730
1
    auto& partition_data_column = struct_column->get_column(3);
731
1
    file_path_column.reserve(rows);
732
1
    row_pos_column.reserve(rows);
733
1
    spec_id_column.reserve(rows);
734
1
    partition_data_column.reserve(rows);
735
3
    for (size_t row = 0; row < rows; ++row) {
736
2
        file_path_column.insert_data(file_path.data(), file_path.size());
737
2
        const int64_t row_pos = row_position_column.get_element(row);
738
2
        row_pos_column.insert_data(reinterpret_cast<const char*>(&row_pos), sizeof(row_pos));
739
2
        spec_id_column.insert_data(reinterpret_cast<const char*>(&partition_spec_id),
740
2
                                   sizeof(partition_spec_id));
741
2
        partition_data_column.insert_data(partition_data_json.data(), partition_data_json.size());
742
2
    }
743
1
    if (nullable_column != nullptr) {
744
1
        nullable_column->get_null_map_data().resize_fill(rows, 0);
745
1
    }
746
1
    table_block->replace_by_position(column_idx, std::move(column));
747
1
    return Status::OK();
748
1
}
749
750
Status IcebergTableReader::_materialize_row_lineage_last_updated_sequence_number(
751
8
        Block* table_block, size_t column_idx) {
752
8
    if (_row_lineage_columns.last_updated_sequence_number < 0) {
753
2
        return Status::OK();
754
2
    }
755
6
    auto column = IColumn::mutate(
756
6
            table_block->get_by_position(column_idx).column->convert_to_full_column_if_const());
757
6
    auto* nullable_column = assert_cast<ColumnNullable*>(column.get());
758
6
    auto& null_map = nullable_column->get_null_map_data();
759
6
    auto& data = assert_cast<ColumnInt64&>(*nullable_column->get_nested_column_ptr()).get_data();
760
6
    DORIS_CHECK(null_map.size() == table_block->rows());
761
6
    DORIS_CHECK(data.size() == table_block->rows());
762
20
    for (size_t row = 0; row < table_block->rows(); ++row) {
763
14
        if (null_map[row]) {
764
8
            null_map[row] = 0;
765
8
            data[row] = _row_lineage_columns.last_updated_sequence_number;
766
8
        }
767
14
    }
768
6
    table_block->replace_by_position(column_idx, std::move(column));
769
6
    return Status::OK();
770
8
}
771
772
8
bool IcebergTableReader::_need_row_lineage_row_id() const {
773
8
    if (_data_reader.column_mapper != nullptr) {
774
7
        for (const auto& mapping : _data_reader.column_mapper->mappings()) {
775
7
            if (mapping.virtual_column_type == format::TableVirtualColumnType::ROW_ID) {
776
7
                return true;
777
7
            }
778
7
        }
779
7
    }
780
1
    return std::ranges::any_of(_projected_columns, is_projected_row_lineage_row_id);
781
8
}
782
783
13
bool IcebergTableReader::_need_iceberg_rowid() const {
784
13
    if (_data_reader.column_mapper != nullptr) {
785
17
        for (const auto& mapping : _data_reader.column_mapper->mappings()) {
786
17
            if (mapping.virtual_column_type == format::TableVirtualColumnType::ICEBERG_ROWID) {
787
1
                return true;
788
1
            }
789
17
        }
790
13
    }
791
12
    return std::ranges::any_of(_projected_columns, is_projected_iceberg_rowid);
792
13
}
793
794
} // namespace doris::format::iceberg