Coverage Report

Created: 2026-06-03 21:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format/table/transactional_hive_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/transactional_hive_reader.h"
19
20
#include <re2/re2.h>
21
22
#include <utility>
23
24
#include "core/data_type/data_type_factory.hpp"
25
#include "format/orc/vorc_reader.h"
26
#include "format/table/table_schema_change_helper.h"
27
#include "transactional_hive_common.h"
28
29
namespace doris {
30
31
namespace io {
32
struct IOContext;
33
} // namespace io
34
class VExprContext;
35
} // namespace doris
36
37
namespace doris {
38
39
TransactionalHiveReader::TransactionalHiveReader(RuntimeProfile* profile, RuntimeState* state,
40
                                                 const TFileScanRangeParams& params,
41
                                                 const TFileRangeDesc& range, size_t batch_size,
42
                                                 const std::string& ctz, io::IOContext* io_ctx,
43
                                                 FileMetaCache* meta_cache)
44
0
        : OrcReader(profile, state, params, range, batch_size, ctz, io_ctx, meta_cache, false) {
45
0
    _init_transactional_hive_profile();
46
0
}
47
48
TransactionalHiveReader::TransactionalHiveReader(RuntimeProfile* profile, RuntimeState* state,
49
                                                 const TFileScanRangeParams& params,
50
                                                 const TFileRangeDesc& range, size_t batch_size,
51
                                                 const std::string& ctz,
52
                                                 std::shared_ptr<io::IOContext> io_ctx_holder,
53
                                                 FileMetaCache* meta_cache)
54
0
        : OrcReader(profile, state, params, range, batch_size, ctz, std::move(io_ctx_holder),
55
0
                    meta_cache, false) {
56
0
    _init_transactional_hive_profile();
57
0
}
58
59
0
void TransactionalHiveReader::_init_transactional_hive_profile() {
60
0
    static const char* transactional_hive_profile = "TransactionalHiveProfile";
61
0
    ADD_TIMER(get_profile(), transactional_hive_profile);
62
0
    _transactional_orc_profile.num_delete_files = ADD_CHILD_COUNTER(
63
0
            get_profile(), "NumDeleteFiles", TUnit::UNIT, transactional_hive_profile);
64
0
    _transactional_orc_profile.num_delete_rows = ADD_CHILD_COUNTER(
65
0
            get_profile(), "NumDeleteRows", TUnit::UNIT, transactional_hive_profile);
66
0
    _transactional_orc_profile.delete_files_read_time =
67
0
            ADD_CHILD_TIMER(get_profile(), "DeleteFileReadTime", transactional_hive_profile);
68
0
}
69
70
// ============================================================================
71
// on_before_init_reader: ACID schema mapping
72
// ============================================================================
73
0
Status TransactionalHiveReader::on_before_init_reader(ReaderInitContext* ctx) {
74
0
    _column_descs = ctx->column_descs;
75
0
    _fill_col_name_to_block_idx = ctx->col_name_to_block_idx;
76
0
    RETURN_IF_ERROR(
77
0
            _extract_partition_values(*ctx->range, ctx->tuple_descriptor, _fill_partition_values));
78
0
    for (auto& desc : *ctx->column_descs) {
79
0
        if (desc.category == ColumnCategory::REGULAR ||
80
0
            desc.category == ColumnCategory::GENERATED) {
81
0
            _col_names.push_back(desc.name);
82
0
        } else if (desc.category == ColumnCategory::SYNTHESIZED &&
83
0
                   desc.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
84
0
            auto topn_row_id_column_iter = _create_topn_row_id_column_iterator();
85
0
            this->register_synthesized_column_handler(
86
0
                    desc.name,
87
0
                    [iter = std::move(topn_row_id_column_iter), this, &desc](
88
0
                            Block* block, size_t rows) -> Status {
89
0
                        return fill_topn_row_id(iter, desc.name, block, rows);
90
0
                    });
91
0
            continue;
92
0
        }
93
0
    }
94
95
0
    _is_acid = true;
96
    // Add ACID column names (originalTransaction, bucket, rowId, etc.)
97
0
    _col_names.insert(_col_names.end(), TransactionalHive::READ_ROW_COLUMN_NAMES_LOWER_CASE.begin(),
98
0
                      TransactionalHive::READ_ROW_COLUMN_NAMES_LOWER_CASE.end());
99
0
    ctx->column_names = _col_names;
100
101
    // Get ORC file type
102
0
    const orc::Type* orc_type_ptr = nullptr;
103
0
    RETURN_IF_ERROR(get_file_type(&orc_type_ptr));
104
0
    const auto& orc_type = *orc_type_ptr;
105
106
    // Add ACID metadata columns to table_info_node
107
0
    for (auto idx = 0; idx < TransactionalHive::READ_ROW_COLUMN_NAMES_LOWER_CASE.size(); idx++) {
108
0
        table_info_node_ptr->add_children(TransactionalHive::READ_ROW_COLUMN_NAMES_LOWER_CASE[idx],
109
0
                                          TransactionalHive::READ_ROW_COLUMN_NAMES[idx],
110
0
                                          std::make_shared<ScalarNode>());
111
0
    }
112
113
    // https://issues.apache.org/jira/browse/HIVE-15190
114
0
    auto row_orc_type = orc_type.getSubtype(TransactionalHive::ROW_OFFSET);
115
0
    std::vector<std::string> row_names;
116
0
    std::map<std::string, uint64_t> row_names_map;
117
0
    for (uint64_t idx = 0; idx < row_orc_type->getSubtypeCount(); idx++) {
118
0
        const auto& file_column_name = row_orc_type->getFieldName(idx);
119
0
        row_names.emplace_back(file_column_name);
120
0
        row_names_map.emplace(file_column_name, idx);
121
0
    }
122
123
    // Match table columns to file columns by name
124
0
    for (const auto& slot : ctx->tuple_descriptor->slots()) {
125
0
        const auto& slot_name = slot->col_name();
126
127
0
        if (std::count(TransactionalHive::READ_ROW_COLUMN_NAMES_LOWER_CASE.begin(),
128
0
                       TransactionalHive::READ_ROW_COLUMN_NAMES_LOWER_CASE.end(), slot_name) > 0) {
129
0
            return Status::InternalError("Column {} conflicts with ACID metadata column",
130
0
                                         slot_name);
131
0
        }
132
133
0
        if (row_names_map.contains(slot_name)) {
134
0
            std::shared_ptr<Node> child_node = nullptr;
135
0
            RETURN_IF_ERROR(BuildTableInfoUtil::by_orc_name(
136
0
                    slot->type(), row_orc_type->getSubtype(row_names_map[slot_name]), child_node));
137
0
            auto file_column_name = fmt::format(
138
0
                    "{}.{}", TransactionalHive::ACID_COLUMN_NAMES[TransactionalHive::ROW_OFFSET],
139
0
                    slot_name);
140
0
            table_info_node_ptr->add_children(slot_name, file_column_name, child_node);
141
0
        } else {
142
0
            table_info_node_ptr->add_not_exist_children(slot_name);
143
0
        }
144
0
    }
145
0
    ctx->table_info_node = table_info_node_ptr;
146
0
    return Status::OK();
147
0
}
148
149
// ============================================================================
150
// on_after_init_reader: read delete delta files
151
// ============================================================================
152
0
Status TransactionalHiveReader::on_after_init_reader(ReaderInitContext* /*ctx*/) {
153
0
    std::string data_file_path = get_scan_range().path;
154
    // the path in _range has the namenode prefix removed,
155
    // and the file_path in delete file is full path, so we should add it back.
156
0
    if (get_scan_params().__isset.hdfs_params && get_scan_params().hdfs_params.__isset.fs_name) {
157
0
        std::string fs_name = get_scan_params().hdfs_params.fs_name;
158
0
        if (!starts_with(data_file_path, fs_name)) {
159
0
            data_file_path = fs_name + data_file_path;
160
0
        }
161
0
    }
162
163
0
    std::vector<std::string> delete_file_col_names;
164
0
    int64_t num_delete_rows = 0;
165
0
    int64_t num_delete_files = 0;
166
0
    std::filesystem::path file_path(data_file_path);
167
168
    // bucket_xxx_attemptId => bucket_xxx
169
0
    auto remove_bucket_attemptId = [](const std::string& str) {
170
0
        re2::RE2 pattern("^bucket_\\d+_\\d+$");
171
0
        if (re2::RE2::FullMatch(str, pattern)) {
172
0
            size_t pos = str.rfind('_');
173
0
            if (pos != std::string::npos) {
174
0
                return str.substr(0, pos);
175
0
            }
176
0
        }
177
0
        return str;
178
0
    };
179
180
0
    SCOPED_TIMER(_transactional_orc_profile.delete_files_read_time);
181
0
    for (const auto& delete_delta :
182
0
         get_scan_range().table_format_params.transactional_hive_params.delete_deltas) {
183
0
        const std::string file_name = file_path.filename().string();
184
185
0
        std::vector<std::string> delete_delta_file_names;
186
0
        for (const auto& x : delete_delta.file_names) {
187
0
            delete_delta_file_names.emplace_back(remove_bucket_attemptId(x));
188
0
        }
189
0
        auto iter = std::find(delete_delta_file_names.begin(), delete_delta_file_names.end(),
190
0
                              remove_bucket_attemptId(file_name));
191
0
        if (iter == delete_delta_file_names.end()) {
192
0
            continue;
193
0
        }
194
0
        auto delete_file =
195
0
                fmt::format("{}/{}", delete_delta.directory_location,
196
0
                            delete_delta.file_names[iter - delete_delta_file_names.begin()]);
197
198
0
        TFileRangeDesc delete_range;
199
0
        delete_range.__set_fs_name(get_scan_range().fs_name);
200
0
        delete_range.path = delete_file;
201
0
        delete_range.start_offset = 0;
202
0
        delete_range.size = -1;
203
0
        delete_range.file_size = -1;
204
205
0
        OrcReader delete_reader(get_profile(), get_state(), get_scan_params(), delete_range,
206
0
                                256 /*batch_size*/, get_state()->timezone(), get_io_ctx(),
207
0
                                _meta_cache, false);
208
209
0
        auto acid_info_node = std::make_shared<StructNode>();
210
0
        for (auto idx = 0; idx < TransactionalHive::DELETE_ROW_COLUMN_NAMES_LOWER_CASE.size();
211
0
             idx++) {
212
0
            auto const& table_column_name =
213
0
                    TransactionalHive::DELETE_ROW_COLUMN_NAMES_LOWER_CASE[idx];
214
0
            auto const& file_column_name = TransactionalHive::DELETE_ROW_COLUMN_NAMES[idx];
215
0
            acid_info_node->add_children(table_column_name, file_column_name,
216
0
                                         std::make_shared<ScalarNode>());
217
0
        }
218
219
0
        OrcInitContext delete_ctx;
220
0
        delete_ctx.column_names.assign(
221
0
                TransactionalHive::DELETE_ROW_COLUMN_NAMES_LOWER_CASE.begin(),
222
0
                TransactionalHive::DELETE_ROW_COLUMN_NAMES_LOWER_CASE.end());
223
0
        delete_ctx.col_name_to_block_idx = const_cast<std::unordered_map<std::string, uint32_t>*>(
224
0
                &TransactionalHive::DELETE_COL_NAME_TO_BLOCK_IDX);
225
0
        delete_ctx.table_info_node = acid_info_node;
226
0
        RETURN_IF_ERROR(delete_reader.init_reader(&delete_ctx));
227
228
0
        bool eof = false;
229
0
        while (!eof) {
230
0
            Block block;
231
0
            for (const auto& i : TransactionalHive::DELETE_ROW_PARAMS) {
232
0
                DataTypePtr data_type = DataTypeFactory::instance().create_data_type(i.type, false);
233
0
                MutableColumnPtr data_column = data_type->create_column();
234
0
                block.insert(ColumnWithTypeAndName(std::move(data_column), data_type,
235
0
                                                   i.column_lower_case));
236
0
            }
237
0
            eof = false;
238
0
            size_t read_rows = 0;
239
0
            RETURN_IF_ERROR(delete_reader.get_next_block(&block, &read_rows, &eof));
240
0
            if (read_rows > 0) {
241
0
                static int ORIGINAL_TRANSACTION_INDEX = 0;
242
0
                static int BUCKET_ID_INDEX = 1;
243
0
                static int ROW_ID_INDEX = 2;
244
0
                const auto& original_transaction_column = assert_cast<const ColumnInt64&>(
245
0
                        *block.get_by_position(ORIGINAL_TRANSACTION_INDEX).column);
246
0
                const auto& bucket_id_column = assert_cast<const ColumnInt32&>(
247
0
                        *block.get_by_position(BUCKET_ID_INDEX).column);
248
0
                const auto& row_id_column = assert_cast<const ColumnInt64&>(
249
0
                        *block.get_by_position(ROW_ID_INDEX).column);
250
251
0
                DCHECK_EQ(original_transaction_column.size(), read_rows);
252
0
                DCHECK_EQ(bucket_id_column.size(), read_rows);
253
0
                DCHECK_EQ(row_id_column.size(), read_rows);
254
255
0
                for (int i = 0; i < read_rows; ++i) {
256
0
                    Int64 original_transaction = original_transaction_column.get_int(i);
257
0
                    Int64 bucket_id = bucket_id_column.get_int(i);
258
0
                    Int64 row_id = row_id_column.get_int(i);
259
0
                    AcidRowID delete_row_id = {original_transaction, bucket_id, row_id};
260
0
                    _acid_delete_rows.insert(delete_row_id);
261
0
                    ++num_delete_rows;
262
0
                }
263
0
            }
264
0
        }
265
0
        ++num_delete_files;
266
0
    }
267
0
    if (num_delete_rows > 0) {
268
0
        set_push_down_agg_type(TPushAggOp::NONE);
269
0
        set_delete_rows(&_acid_delete_rows);
270
0
        COUNTER_UPDATE(_transactional_orc_profile.num_delete_files, num_delete_files);
271
0
        COUNTER_UPDATE(_transactional_orc_profile.num_delete_rows, num_delete_rows);
272
0
    }
273
0
    return Status::OK();
274
0
}
275
276
// ============================================================================
277
// on_before_read_block: expand ACID columns into block
278
// TODO: Consider caching ACID column templates at init time to avoid repeated
279
// create_column + map update on every batch. Requires a block template mechanism.
280
// ============================================================================
281
0
Status TransactionalHiveReader::on_before_read_block(Block* block) {
282
0
    for (const auto& i : TransactionalHive::READ_PARAMS) {
283
0
        DataTypePtr data_type = get_data_type_with_default_argument(
284
0
                DataTypeFactory::instance().create_data_type(i.type, false));
285
0
        MutableColumnPtr data_column = data_type->create_column();
286
0
        (*col_name_to_block_idx_ref())[i.column_lower_case] =
287
0
                static_cast<uint32_t>(block->columns());
288
0
        block->insert(
289
0
                ColumnWithTypeAndName(std::move(data_column), data_type, i.column_lower_case));
290
0
    }
291
0
    return Status::OK();
292
0
}
293
294
// ============================================================================
295
// on_after_read_block: shrink ACID columns from block
296
// ============================================================================
297
0
Status TransactionalHiveReader::on_after_read_block(Block* block, size_t* /*read_rows*/) {
298
0
    Block::erase_useless_column(block, block->columns() - TransactionalHive::READ_PARAMS.size());
299
0
    for (const auto& i : TransactionalHive::READ_PARAMS) {
300
0
        col_name_to_block_idx_ref()->erase(i.column_lower_case);
301
0
    }
302
0
    return Status::OK();
303
0
}
304
305
} // namespace doris