Coverage Report

Created: 2026-06-06 15:23

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