Coverage Report

Created: 2026-03-17 07:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/tablet_info.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "storage/tablet_info.h"
19
20
#include <butil/logging.h>
21
#include <gen_cpp/Descriptors_types.h>
22
#include <gen_cpp/Exprs_types.h>
23
#include <gen_cpp/Partitions_types.h>
24
#include <gen_cpp/Types_types.h>
25
#include <gen_cpp/descriptors.pb.h>
26
#include <gen_cpp/olap_file.pb.h>
27
#include <glog/logging.h>
28
29
#include <algorithm>
30
#include <cstddef>
31
#include <cstdint>
32
#include <memory>
33
#include <ostream>
34
#include <string>
35
#include <tuple>
36
37
#include "common/exception.h"
38
#include "common/logging.h"
39
#include "common/status.h"
40
#include "core/column/column.h"
41
#include "core/data_type/data_type.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/value/large_int_value.h"
46
#include "runtime/descriptors.h"
47
#include "runtime/memory/mem_tracker.h"
48
#include "storage/tablet/tablet_schema.h"
49
#include "util/raw_value.h"
50
#include "util/string_parser.hpp"
51
#include "util/string_util.h"
52
// NOLINTNEXTLINE(unused-includes)
53
#include "core/value/vdatetime_value.h"
54
#include "exprs/function/cast/cast_to_timestamptz.h"
55
#include "exprs/vexpr_context.h" // IWYU pragma: keep
56
#include "exprs/vliteral.h"
57
58
namespace doris {
59
#include "common/compile_check_begin.h"
60
61
4.44k
void OlapTableIndexSchema::to_protobuf(POlapTableIndexSchema* pindex) const {
62
4.44k
    pindex->set_id(index_id);
63
4.44k
    pindex->set_schema_hash(schema_hash);
64
39.1k
    for (auto* slot : slots) {
65
39.1k
        pindex->add_columns(slot->col_name());
66
39.1k
    }
67
40.6k
    for (auto* column : columns) {
68
40.6k
        column->to_schema_pb(pindex->add_columns_desc());
69
40.6k
    }
70
4.44k
    for (auto* index : indexes) {
71
0
        index->to_schema_pb(pindex->add_indexes_desc());
72
0
    }
73
4.44k
}
74
75
bool VOlapTablePartKeyComparator::operator()(const BlockRowWithIndicator& lhs,
76
387k
                                             const BlockRowWithIndicator& rhs) const {
77
387k
    Block* l_block = std::get<0>(lhs);
78
387k
    Block* r_block = std::get<0>(rhs);
79
387k
    int32_t l_row = std::get<1>(lhs);
80
387k
    int32_t r_row = std::get<1>(rhs);
81
387k
    bool l_use_new = std::get<2>(lhs);
82
387k
    bool r_use_new = std::get<2>(rhs);
83
84
387k
    VLOG_TRACE << '\n' << l_block->dump_data() << '\n' << r_block->dump_data();
85
86
387k
    if (l_row == -1) {
87
0
        return false;
88
387k
    } else if (r_row == -1) {
89
39.0k
        return true;
90
39.0k
    }
91
92
348k
    if (_param_locs.empty()) { // no transform, use origin column
93
348k
        for (auto slot_loc : _slot_locs) {
94
348k
            auto res = l_block->get_by_position(slot_loc).column->compare_at(
95
348k
                    l_row, r_row, *r_block->get_by_position(slot_loc).column, -1);
96
348k
            if (res != 0) {
97
346k
                return res < 0;
98
346k
            }
99
348k
        }
100
348k
    } else { // use transformed column to compare
101
37
        DCHECK(_slot_locs.size() == _param_locs.size())
102
0
                << _slot_locs.size() << ' ' << _param_locs.size();
103
104
37
        const std::vector<uint16_t>* l_index = l_use_new ? &_param_locs : &_slot_locs;
105
37
        const std::vector<uint16_t>* r_index = r_use_new ? &_param_locs : &_slot_locs;
106
107
49
        for (int i = 0; i < _slot_locs.size(); i++) {
108
37
            ColumnPtr l_col = l_block->get_by_position((*l_index)[i]).column;
109
37
            ColumnPtr r_col = r_block->get_by_position((*r_index)[i]).column;
110
111
37
            auto res = l_col->compare_at(l_row, r_row, *r_col, -1);
112
37
            if (res != 0) {
113
25
                return res < 0;
114
25
            }
115
37
        }
116
37
    }
117
118
    // equal, return false
119
2.15k
    return false;
120
348k
}
121
122
2.33k
Status OlapTableSchemaParam::init(const POlapTableSchemaParam& pschema) {
123
2.33k
    _db_id = pschema.db_id();
124
2.33k
    _table_id = pschema.table_id();
125
2.33k
    _version = pschema.version();
126
2.33k
    if (pschema.has_unique_key_update_mode()) {
127
2.33k
        _unique_key_update_mode = pschema.unique_key_update_mode();
128
2.33k
        if (pschema.has_sequence_map_col_unique_id()) {
129
2.33k
            _sequence_map_col_uid = pschema.sequence_map_col_unique_id();
130
2.33k
        }
131
2.33k
    } else {
132
        // for backward compatibility
133
0
        if (pschema.has_partial_update() && pschema.partial_update()) {
134
0
            _unique_key_update_mode = UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS;
135
0
        } else {
136
0
            _unique_key_update_mode = UniqueKeyUpdateModePB::UPSERT;
137
0
        }
138
0
    }
139
2.33k
    _is_strict_mode = pschema.is_strict_mode();
140
2.33k
    if (_unique_key_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
141
110
        _auto_increment_column = pschema.auto_increment_column();
142
110
        if (!_auto_increment_column.empty() && pschema.auto_increment_column_unique_id() == -1) {
143
0
            return Status::InternalError(
144
0
                    "Auto increment column id is not set in FE. Maybe FE is an older version "
145
0
                    "different from BE.");
146
0
        }
147
110
        _auto_increment_column_unique_id = pschema.auto_increment_column_unique_id();
148
110
    }
149
2.33k
    if (_unique_key_update_mode != UniqueKeyUpdateModePB::UPSERT) {
150
110
        if (pschema.has_partial_update_new_key_policy()) {
151
110
            _partial_update_new_row_policy = pschema.partial_update_new_key_policy();
152
110
        }
153
110
    }
154
2.33k
    _timestamp_ms = pschema.timestamp_ms();
155
2.33k
    if (pschema.has_nano_seconds()) {
156
2.33k
        _nano_seconds = pschema.nano_seconds();
157
2.33k
    }
158
2.33k
    _timezone = pschema.timezone();
159
160
2.33k
    for (const auto& col : pschema.partial_update_input_columns()) {
161
696
        _partial_update_input_columns.insert(col);
162
696
    }
163
2.33k
    std::unordered_map<std::string, SlotDescriptor*> slots_map;
164
165
2.33k
    _tuple_desc = _obj_pool.add(new TupleDescriptor(pschema.tuple_desc()));
166
167
22.4k
    for (const auto& p_slot_desc : pschema.slot_descs()) {
168
22.4k
        auto* slot_desc = _obj_pool.add(new SlotDescriptor(p_slot_desc));
169
22.4k
        _tuple_desc->add_slot(slot_desc);
170
22.4k
        std::string data_type;
171
22.4k
        EnumToString(TPrimitiveType, to_thrift(slot_desc->col_type()), data_type);
172
22.4k
        std::string is_null_str = slot_desc->is_nullable() ? "true" : "false";
173
22.4k
        std::string data_type_str =
174
22.4k
                std::to_string(int64_t(TabletColumn::get_field_type_by_string(data_type)));
175
22.4k
        slots_map.emplace(to_lower(slot_desc->col_name()) + "+" + data_type_str + is_null_str,
176
22.4k
                          slot_desc);
177
22.4k
    }
178
179
2.34k
    for (const auto& p_index : pschema.indexes()) {
180
2.34k
        auto* index = _obj_pool.add(new OlapTableIndexSchema());
181
2.34k
        index->index_id = p_index.id();
182
2.34k
        index->schema_hash = p_index.schema_hash();
183
23.1k
        for (const auto& pcolumn_desc : p_index.columns_desc()) {
184
23.1k
            if (_unique_key_update_mode != UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS ||
185
23.1k
                _partial_update_input_columns.contains(pcolumn_desc.name())) {
186
22.3k
                std::string is_null_str = pcolumn_desc.is_nullable() ? "true" : "false";
187
22.3k
                std::string data_type_str = std::to_string(
188
22.3k
                        int64_t(TabletColumn::get_field_type_by_string(pcolumn_desc.type())));
189
22.3k
                auto it = slots_map.find(to_lower(pcolumn_desc.name()) + "+" + data_type_str +
190
22.3k
                                         is_null_str);
191
22.3k
                if (it == std::end(slots_map)) {
192
0
                    std::string keys {};
193
0
                    for (const auto& [key, _] : slots_map) {
194
0
                        keys += fmt::format("{},", key);
195
0
                    }
196
0
                    LOG_EVERY_SECOND(WARNING) << fmt::format(
197
0
                            "[OlapTableSchemaParam::init(const POlapTableSchemaParam& pschema)]: "
198
0
                            "unknown index column, column={}, type={}, data_type_str={}, "
199
0
                            "is_null_str={}, slots_map.keys()=[{}], {}\npschema={}",
200
0
                            pcolumn_desc.name(), pcolumn_desc.type(), data_type_str, is_null_str,
201
0
                            keys, debug_string(), pschema.ShortDebugString());
202
203
0
                    return Status::InternalError("unknown index column, column={}, type={}",
204
0
                                                 pcolumn_desc.name(), pcolumn_desc.type());
205
0
                }
206
22.3k
                index->slots.emplace_back(it->second);
207
22.3k
            }
208
23.1k
            TabletColumn* tc = _obj_pool.add(new TabletColumn());
209
23.1k
            tc->init_from_pb(pcolumn_desc);
210
23.1k
            index->columns.emplace_back(tc);
211
23.1k
        }
212
2.34k
        for (const auto& pindex_desc : p_index.indexes_desc()) {
213
0
            TabletIndex* ti = _obj_pool.add(new TabletIndex());
214
0
            ti->init_from_pb(pindex_desc);
215
0
            index->indexes.emplace_back(ti);
216
0
        }
217
2.34k
        _indexes.emplace_back(index);
218
2.34k
    }
219
220
2.33k
    std::sort(_indexes.begin(), _indexes.end(),
221
2.33k
              [](const OlapTableIndexSchema* lhs, const OlapTableIndexSchema* rhs) {
222
28
                  return lhs->index_id < rhs->index_id;
223
28
              });
224
2.33k
    return Status::OK();
225
2.33k
}
226
227
8.40k
Status OlapTableSchemaParam::init_unique_key_update_mode(const TOlapTableSchemaParam& tschema) {
228
8.40k
    if (tschema.__isset.unique_key_update_mode) {
229
8.38k
        switch (tschema.unique_key_update_mode) {
230
7.69k
        case doris::TUniqueKeyUpdateMode::UPSERT: {
231
7.69k
            _unique_key_update_mode = UniqueKeyUpdateModePB::UPSERT;
232
7.69k
            break;
233
0
        }
234
692
        case doris::TUniqueKeyUpdateMode::UPDATE_FIXED_COLUMNS: {
235
692
            _unique_key_update_mode = UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS;
236
692
            break;
237
0
        }
238
0
        case doris::TUniqueKeyUpdateMode::UPDATE_FLEXIBLE_COLUMNS: {
239
0
            _unique_key_update_mode = UniqueKeyUpdateModePB::UPDATE_FLEXIBLE_COLUMNS;
240
0
            break;
241
0
        }
242
0
        default: {
243
0
            return Status::InternalError(
244
0
                    "Unknown unique_key_update_mode: {}, should be one of "
245
0
                    "UPSERT/UPDATE_FIXED_COLUMNS/UPDATE_FLEXIBLE_COLUMNS",
246
0
                    tschema.unique_key_update_mode);
247
0
        }
248
8.38k
        }
249
8.38k
        if (tschema.__isset.sequence_map_col_unique_id) {
250
8.38k
            _sequence_map_col_uid = tschema.sequence_map_col_unique_id;
251
8.38k
        }
252
8.38k
    } else {
253
        // for backward compatibility
254
21
        if (tschema.__isset.is_partial_update && tschema.is_partial_update) {
255
0
            _unique_key_update_mode = UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS;
256
21
        } else {
257
21
            _unique_key_update_mode = UniqueKeyUpdateModePB::UPSERT;
258
21
        }
259
21
    }
260
8.40k
    return Status::OK();
261
8.40k
}
262
263
8.40k
Status OlapTableSchemaParam::init(const TOlapTableSchemaParam& tschema) {
264
8.40k
    _db_id = tschema.db_id;
265
8.40k
    _table_id = tschema.table_id;
266
8.40k
    _version = tschema.version;
267
8.40k
    RETURN_IF_ERROR(init_unique_key_update_mode(tschema));
268
8.40k
    if (tschema.__isset.is_strict_mode) {
269
8.39k
        _is_strict_mode = tschema.is_strict_mode;
270
8.39k
    }
271
8.40k
    if (_unique_key_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
272
694
        _auto_increment_column = tschema.auto_increment_column;
273
694
        if (!_auto_increment_column.empty() && tschema.auto_increment_column_unique_id == -1) {
274
0
            return Status::InternalError(
275
0
                    "Auto increment column id is not set in FE. Maybe FE is an older version "
276
0
                    "different from BE.");
277
0
        }
278
694
        _auto_increment_column_unique_id = tschema.auto_increment_column_unique_id;
279
694
    }
280
281
8.40k
    if (_unique_key_update_mode != UniqueKeyUpdateModePB::UPSERT) {
282
694
        if (tschema.__isset.partial_update_new_key_policy) {
283
694
            switch (tschema.partial_update_new_key_policy) {
284
694
            case doris::TPartialUpdateNewRowPolicy::APPEND: {
285
694
                _partial_update_new_row_policy = PartialUpdateNewRowPolicyPB::APPEND;
286
694
                break;
287
0
            }
288
0
            case doris::TPartialUpdateNewRowPolicy::ERROR: {
289
0
                _partial_update_new_row_policy = PartialUpdateNewRowPolicyPB::ERROR;
290
0
                break;
291
0
            }
292
0
            default: {
293
0
                return Status::InvalidArgument(
294
0
                        "Unknown partial_update_new_key_behavior: {}, should be one of "
295
0
                        "'APPEND' or 'ERROR'",
296
0
                        tschema.partial_update_new_key_policy);
297
0
            }
298
694
            }
299
694
        }
300
694
    }
301
302
8.40k
    for (const auto& tcolumn : tschema.partial_update_input_columns) {
303
2.82k
        _partial_update_input_columns.insert(tcolumn);
304
2.82k
    }
305
8.40k
    std::unordered_map<std::string, SlotDescriptor*> slots_map;
306
8.40k
    _tuple_desc = _obj_pool.add(new TupleDescriptor(tschema.tuple_desc));
307
59.1k
    for (const auto& t_slot_desc : tschema.slot_descs) {
308
59.1k
        auto* slot_desc = _obj_pool.add(new SlotDescriptor(t_slot_desc));
309
59.1k
        _tuple_desc->add_slot(slot_desc);
310
59.1k
        std::string is_null_str = slot_desc->is_nullable() ? "true" : "false";
311
59.1k
        std::string data_type_str = std::to_string(int64_t(slot_desc->col_type()));
312
59.1k
        slots_map.emplace(to_lower(slot_desc->col_name()) + "+" + data_type_str + is_null_str,
313
59.1k
                          slot_desc);
314
59.1k
    }
315
316
8.42k
    for (const auto& t_index : tschema.indexes) {
317
8.42k
        std::unordered_map<std::string, int32_t> index_slots_map;
318
8.42k
        auto* index = _obj_pool.add(new OlapTableIndexSchema());
319
8.42k
        index->index_id = t_index.id;
320
8.42k
        index->schema_hash = t_index.schema_hash;
321
61.9k
        for (const auto& tcolumn_desc : t_index.columns_desc) {
322
61.9k
            if (_unique_key_update_mode != UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS ||
323
61.9k
                _partial_update_input_columns.contains(tcolumn_desc.column_name)) {
324
58.9k
                std::string is_null_str = tcolumn_desc.is_allow_null ? "true" : "false";
325
58.9k
                std::string data_type_str =
326
58.9k
                        std::to_string(int64_t(thrift_to_type(tcolumn_desc.column_type.type)));
327
58.9k
                auto it = slots_map.find(to_lower(tcolumn_desc.column_name) + "+" + data_type_str +
328
58.9k
                                         is_null_str);
329
58.9k
                if (it == slots_map.end()) {
330
0
                    std::stringstream ss;
331
0
                    ss << tschema;
332
0
                    std::string keys {};
333
0
                    for (const auto& [key, _] : slots_map) {
334
0
                        keys += fmt::format("{},", key);
335
0
                    }
336
0
                    LOG_EVERY_SECOND(WARNING) << fmt::format(
337
0
                            "[OlapTableSchemaParam::init(const TOlapTableSchemaParam& tschema)]: "
338
0
                            "unknown index column, column={}, type={}, data_type_str={}, "
339
0
                            "is_null_str={}, slots_map.keys()=[{}], {}\ntschema={}",
340
0
                            tcolumn_desc.column_name, tcolumn_desc.column_type.type, data_type_str,
341
0
                            is_null_str, keys, debug_string(), ss.str());
342
0
                    return Status::InternalError("unknown index column, column={}, type={}",
343
0
                                                 tcolumn_desc.column_name,
344
0
                                                 tcolumn_desc.column_type.type);
345
0
                }
346
58.9k
                index->slots.emplace_back(it->second);
347
58.9k
            }
348
61.9k
            index_slots_map.emplace(to_lower(tcolumn_desc.column_name), tcolumn_desc.col_unique_id);
349
61.9k
            TabletColumn* tc = _obj_pool.add(new TabletColumn());
350
61.9k
            tc->init_from_thrift(tcolumn_desc);
351
61.9k
            index->columns.emplace_back(tc);
352
61.9k
        }
353
8.42k
        if (t_index.__isset.indexes_desc) {
354
8.38k
            for (const auto& tindex_desc : t_index.indexes_desc) {
355
0
                std::vector<int32_t> column_unique_ids(tindex_desc.columns.size());
356
0
                for (size_t i = 0; i < tindex_desc.columns.size(); i++) {
357
0
                    auto it = index_slots_map.find(to_lower(tindex_desc.columns[i]));
358
0
                    if (it != index_slots_map.end()) {
359
0
                        column_unique_ids[i] = it->second;
360
0
                    }
361
0
                }
362
0
                TabletIndex* ti = _obj_pool.add(new TabletIndex());
363
0
                ti->init_from_thrift(tindex_desc, column_unique_ids);
364
0
                index->indexes.emplace_back(ti);
365
0
            }
366
8.38k
        }
367
8.42k
        if (t_index.__isset.where_clause) {
368
0
            RETURN_IF_ERROR(VExpr::create_expr_tree(t_index.where_clause, index->where_clause));
369
0
        }
370
8.42k
        _indexes.emplace_back(index);
371
8.42k
    }
372
373
8.40k
    std::sort(_indexes.begin(), _indexes.end(),
374
8.40k
              [](const OlapTableIndexSchema* lhs, const OlapTableIndexSchema* rhs) {
375
32
                  return lhs->index_id < rhs->index_id;
376
32
              });
377
8.40k
    return Status::OK();
378
8.40k
}
379
380
4.43k
void OlapTableSchemaParam::to_protobuf(POlapTableSchemaParam* pschema) const {
381
4.43k
    pschema->set_db_id(_db_id);
382
4.43k
    pschema->set_table_id(_table_id);
383
4.43k
    pschema->set_version(_version);
384
4.43k
    pschema->set_unique_key_update_mode(_unique_key_update_mode);
385
4.43k
    if (_unique_key_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
386
        // for backward compatibility
387
330
        pschema->set_partial_update(true);
388
330
    }
389
4.43k
    pschema->set_partial_update_new_key_policy(_partial_update_new_row_policy);
390
4.43k
    pschema->set_is_strict_mode(_is_strict_mode);
391
4.43k
    pschema->set_auto_increment_column(_auto_increment_column);
392
4.43k
    pschema->set_auto_increment_column_unique_id(_auto_increment_column_unique_id);
393
4.43k
    pschema->set_timestamp_ms(_timestamp_ms);
394
4.43k
    pschema->set_timezone(_timezone);
395
4.43k
    pschema->set_nano_seconds(_nano_seconds);
396
4.43k
    pschema->set_sequence_map_col_unique_id(_sequence_map_col_uid);
397
4.43k
    for (auto col : _partial_update_input_columns) {
398
1.36k
        *pschema->add_partial_update_input_columns() = col;
399
1.36k
    }
400
4.43k
    _tuple_desc->to_protobuf(pschema->mutable_tuple_desc());
401
39.2k
    for (auto* slot : _tuple_desc->slots()) {
402
39.2k
        slot->to_protobuf(pschema->add_slot_descs());
403
39.2k
    }
404
4.44k
    for (auto* index : _indexes) {
405
4.44k
        index->to_protobuf(pschema->add_indexes());
406
4.44k
    }
407
4.43k
}
408
409
0
std::string OlapTableSchemaParam::debug_string() const {
410
0
    std::stringstream ss;
411
0
    ss << "tuple_desc=" << _tuple_desc->debug_string();
412
0
    return ss.str();
413
0
}
414
415
VOlapTablePartitionParam::VOlapTablePartitionParam(std::shared_ptr<OlapTableSchemaParam>& schema,
416
                                                   const TOlapTablePartitionParam& t_param)
417
6.25k
        : _schema(schema),
418
6.25k
          _t_param(t_param),
419
6.25k
          _slots(_schema->tuple_desc()->slots()),
420
6.25k
          _mem_tracker(std::make_unique<MemTracker>("OlapTablePartitionParam")),
421
6.25k
          _part_type(t_param.partition_type) {
422
6.27k
    if (t_param.__isset.enable_automatic_partition && t_param.enable_automatic_partition) {
423
50
        _is_auto_partition = true;
424
50
        auto size = t_param.partition_function_exprs.size();
425
50
        _part_func_ctx.resize(size);
426
50
        _partition_function.resize(size);
427
50
        DCHECK((t_param.partition_type == TPartitionType::RANGE_PARTITIONED && size == 1) ||
428
2
               (t_param.partition_type == TPartitionType::LIST_PARTITIONED && size >= 1))
429
2
                << "now support only 1 partition column for auto range partitions. "
430
2
                << t_param.partition_type << " " << size;
431
98
        for (int i = 0; i < size; ++i) {
432
48
            Status st =
433
48
                    VExpr::create_expr_tree(t_param.partition_function_exprs[i], _part_func_ctx[i]);
434
48
            if (!st.ok()) {
435
0
                throw Exception(Status::InternalError("Partition function expr is not valid"),
436
0
                                "Partition function expr is not valid");
437
0
            }
438
48
            _partition_function[i] = _part_func_ctx[i]->root();
439
48
        }
440
50
    }
441
442
6.25k
    if (t_param.__isset.enable_auto_detect_overwrite && t_param.enable_auto_detect_overwrite) {
443
1
        _is_auto_detect_overwrite = true;
444
1
        DCHECK(t_param.__isset.overwrite_group_id);
445
1
        _overwrite_group_id = t_param.overwrite_group_id;
446
1
    }
447
448
6.25k
    if (t_param.__isset.master_address) {
449
40
        _master_address = std::make_shared<TNetworkAddress>(t_param.master_address);
450
40
    }
451
452
6.25k
    if (_is_auto_partition) {
453
        // the nullable mode depends on partition_exprs. not column slots. so use them.
454
18.4E
        DCHECK(_partition_function.size() <= _slots.size())
455
18.4E
                << _partition_function.size() << ", " << _slots.size();
456
457
        // suppose (k0, [k1], [k2]), so get [k1, 0], [k2, 1]
458
48
        std::map<std::string, int> partition_slots_map; // name to idx in part_exprs
459
98
        for (size_t i = 0; i < t_param.partition_columns.size(); i++) {
460
50
            partition_slots_map.emplace(t_param.partition_columns[i], i);
461
50
        }
462
463
        // here we rely on the same order and number of the _part_funcs and _slots in the prefix
464
        // _part_block contains all slots of table.
465
190
        for (auto* slot : _slots) {
466
            // try to replace with partition expr.
467
190
            if (auto it = partition_slots_map.find(slot->col_name());
468
190
                it != partition_slots_map.end()) { // it's a partition column slot
469
50
                auto& expr_type = _partition_function[it->second]->data_type();
470
50
                _partition_block.insert({expr_type->create_column(), expr_type, slot->col_name()});
471
140
            } else {
472
140
                _partition_block.insert({slot->get_empty_mutable_column(),
473
140
                                         slot->get_data_type_ptr(), slot->col_name()});
474
140
            }
475
190
        }
476
18.4E
        VLOG_TRACE << _partition_block.dump_structure();
477
6.21k
    } else {
478
        // we insert all. but not all will be used. it will controlled by _partition_slot_locs
479
41.5k
        for (auto* slot : _slots) {
480
41.5k
            _partition_block.insert({slot->get_empty_mutable_column(), slot->get_data_type_ptr(),
481
41.5k
                                     slot->col_name()});
482
41.5k
        }
483
6.21k
    }
484
6.25k
}
485
486
6.29k
VOlapTablePartitionParam::~VOlapTablePartitionParam() {
487
6.29k
    _mem_tracker->release(_mem_usage);
488
6.29k
}
489
490
6.22k
Status VOlapTablePartitionParam::init() {
491
6.22k
    std::vector<std::string> slot_column_names;
492
41.7k
    for (auto* slot_desc : _schema->tuple_desc()->slots()) {
493
41.7k
        slot_column_names.emplace_back(slot_desc->col_name());
494
41.7k
    }
495
496
6.22k
    auto find_slot_locs = [&slot_column_names](const std::string& slot_name,
497
6.22k
                                               std::vector<uint16_t>& locs,
498
9.83k
                                               const std::string& column_type) {
499
9.83k
        auto it = std::find(slot_column_names.begin(), slot_column_names.end(), slot_name);
500
9.83k
        if (it == slot_column_names.end()) {
501
0
            return Status::InternalError("{} column not found, column ={}", column_type, slot_name);
502
0
        }
503
9.83k
        locs.emplace_back(it - slot_column_names.begin());
504
9.83k
        return Status::OK();
505
9.83k
    };
506
507
    // here we find the partition columns. others maybe non-partition columns/special columns.
508
6.22k
    if (_t_param.__isset.partition_columns) {
509
2.43k
        for (auto& part_col : _t_param.partition_columns) {
510
2.43k
            RETURN_IF_ERROR(find_slot_locs(part_col, _partition_slot_locs, "partition"));
511
2.43k
        }
512
2.40k
    }
513
514
6.22k
    _partitions_map = std::make_unique<
515
6.22k
            std::map<BlockRowWithIndicator, VOlapTablePartition*, VOlapTablePartKeyComparator>>(
516
6.22k
            VOlapTablePartKeyComparator(_partition_slot_locs, _transformed_slot_locs));
517
6.24k
    if (_t_param.__isset.distributed_columns) {
518
7.40k
        for (auto& col : _t_param.distributed_columns) {
519
7.40k
            RETURN_IF_ERROR(find_slot_locs(col, _distributed_slot_locs, "distributed"));
520
7.40k
        }
521
6.24k
    }
522
523
    // for both auto/non-auto partition table.
524
6.22k
    _is_in_partition = _part_type == TPartitionType::type::LIST_PARTITIONED;
525
526
    // initial partitions. if meet dummy partitions only for open BE nodes, not generate key of them for finding
527
6.70k
    for (const auto& t_part : _t_param.partitions) {
528
6.70k
        VOlapTablePartition* part = nullptr;
529
6.70k
        RETURN_IF_ERROR(generate_partition_from(t_part, part));
530
6.70k
        _partitions.emplace_back(part);
531
532
6.70k
        if (!_t_param.partitions_is_fake) {
533
6.68k
            if (_is_in_partition) {
534
1.86k
                for (auto& in_key : part->in_keys) {
535
1.86k
                    _partitions_map->emplace(std::tuple {in_key.first, in_key.second, false}, part);
536
1.86k
                }
537
4.83k
            } else {
538
4.83k
                _partitions_map->emplace(
539
4.83k
                        std::tuple {part->end_key.first, part->end_key.second, false}, part);
540
4.83k
            }
541
6.68k
        }
542
6.70k
    }
543
544
6.22k
    _mem_usage = _partition_block.allocated_bytes();
545
6.22k
    _mem_tracker->consume(_mem_usage);
546
6.22k
    return Status::OK();
547
6.22k
}
548
549
bool VOlapTablePartitionParam::_part_contains(VOlapTablePartition* part,
550
153k
                                              BlockRowWithIndicator key) const {
551
153k
    VOlapTablePartKeyComparator comparator(_partition_slot_locs, _transformed_slot_locs);
552
    // we have used upper_bound to find to ensure key < part.right and this part is closest(right - key is min)
553
    // now we only have to check (key >= part.left). the comparator(a,b) means a < b, so we use anti
554
153k
    return part->start_key.second == -1 /* spj: start_key.second == -1 means only single partition*/
555
153k
           || !comparator(key, std::tuple {part->start_key.first, part->start_key.second, false});
556
153k
}
557
558
// insert value into _partition_block's column
559
// NOLINTBEGIN(readability-function-size)
560
3.83k
static Status _create_partition_key(const TExprNode& t_expr, BlockRow* part_key, uint16_t pos) {
561
3.83k
    auto column = std::move(*part_key->first->get_by_position(pos).column).mutate();
562
    //TODO: use assert_cast before insert_data
563
3.83k
    switch (t_expr.node_type) {
564
2.01k
    case TExprNodeType::DATE_LITERAL: {
565
2.01k
        auto primitive_type =
566
2.01k
                DataTypeFactory::instance().create_data_type(t_expr.type)->get_primitive_type();
567
2.01k
        if (primitive_type == TYPE_DATEV2) {
568
800
            DateV2Value<DateV2ValueType> dt;
569
800
            if (!dt.from_date_str(t_expr.date_literal.value.c_str(),
570
800
                                  t_expr.date_literal.value.size())) {
571
0
                std::stringstream ss;
572
0
                ss << "invalid date literal in partition column, date=" << t_expr.date_literal;
573
0
                return Status::InternalError(ss.str());
574
0
            }
575
800
            column->insert_data(reinterpret_cast<const char*>(&dt), 0);
576
1.21k
        } else if (primitive_type == TYPE_DATETIMEV2) {
577
1.21k
            DateV2Value<DateTimeV2ValueType> dt;
578
1.21k
            const int32_t scale =
579
1.21k
                    t_expr.type.types.empty() ? -1 : t_expr.type.types.front().scalar_type.scale;
580
1.21k
            if (!dt.from_date_str(t_expr.date_literal.value.c_str(),
581
1.21k
                                  t_expr.date_literal.value.size(), scale)) {
582
0
                std::stringstream ss;
583
0
                ss << "invalid date literal in partition column, date=" << t_expr.date_literal;
584
0
                return Status::InternalError(ss.str());
585
0
            }
586
1.21k
            column->insert_data(reinterpret_cast<const char*>(&dt), 0);
587
1.21k
        } else if (primitive_type == TYPE_TIMESTAMPTZ) {
588
0
            TimestampTzValue res;
589
0
            CastParameters params {.status = Status::OK(), .is_strict = true};
590
0
            const int32_t scale =
591
0
                    t_expr.type.types.empty() ? -1 : t_expr.type.types.front().scalar_type.scale;
592
0
            if (!CastToTimstampTz::from_string(
593
0
                        {t_expr.date_literal.value.c_str(), t_expr.date_literal.value.size()}, res,
594
0
                        params, nullptr, scale)) [[unlikely]] {
595
0
                std::stringstream ss;
596
0
                ss << "invalid timestamptz literal in partition column, value="
597
0
                   << t_expr.date_literal;
598
0
                return Status::InternalError(ss.str());
599
0
            } else {
600
0
                column->insert_data(reinterpret_cast<const char*>(&res), 0);
601
0
            }
602
0
        } else {
603
            // TYPE_DATE (DATEV1) or TYPE_DATETIME (DATETIMEV1)
604
0
            VecDateTimeValue dt;
605
0
            if (!dt.from_date_str(t_expr.date_literal.value.c_str(),
606
0
                                  t_expr.date_literal.value.size())) {
607
0
                std::stringstream ss;
608
0
                ss << "invalid date literal in partition column, date=" << t_expr.date_literal;
609
0
                return Status::InternalError(ss.str());
610
0
            }
611
0
            if (DataTypeFactory::instance().create_data_type(t_expr.type)->get_primitive_type() ==
612
0
                TYPE_DATE) {
613
0
                dt.cast_to_date();
614
0
            }
615
0
            column->insert_data(reinterpret_cast<const char*>(&dt), 0);
616
0
        }
617
2.01k
        break;
618
2.01k
    }
619
2.01k
    case TExprNodeType::INT_LITERAL: {
620
876
        switch (t_expr.type.types[0].scalar_type.type) {
621
48
        case TPrimitiveType::TINYINT: {
622
48
            auto value = cast_set<int8_t>(t_expr.int_literal.value);
623
48
            column->insert_data(reinterpret_cast<const char*>(&value), 0);
624
48
            break;
625
0
        }
626
0
        case TPrimitiveType::SMALLINT: {
627
0
            auto value = cast_set<int16_t>(t_expr.int_literal.value);
628
0
            column->insert_data(reinterpret_cast<const char*>(&value), 0);
629
0
            break;
630
0
        }
631
828
        case TPrimitiveType::INT: {
632
828
            auto value = cast_set<int32_t>(t_expr.int_literal.value);
633
828
            column->insert_data(reinterpret_cast<const char*>(&value), 0);
634
828
            break;
635
0
        }
636
0
        default:
637
0
            int64_t value = t_expr.int_literal.value;
638
0
            column->insert_data(reinterpret_cast<const char*>(&value), 0);
639
876
        }
640
878
        break;
641
876
    }
642
878
    case TExprNodeType::LARGE_INT_LITERAL: {
643
0
        StringParser::ParseResult parse_result = StringParser::PARSE_SUCCESS;
644
0
        auto value = StringParser::string_to_int<__int128>(t_expr.large_int_literal.value.c_str(),
645
0
                                                           t_expr.large_int_literal.value.size(),
646
0
                                                           &parse_result);
647
0
        if (parse_result != StringParser::PARSE_SUCCESS) {
648
0
            value = MAX_INT128;
649
0
        }
650
0
        column->insert_data(reinterpret_cast<const char*>(&value), 0);
651
0
        break;
652
876
    }
653
886
    case TExprNodeType::STRING_LITERAL: {
654
886
        size_t len = t_expr.string_literal.value.size();
655
886
        const char* str_val = t_expr.string_literal.value.c_str();
656
886
        column->insert_data(str_val, len);
657
886
        break;
658
876
    }
659
0
    case TExprNodeType::BOOL_LITERAL: {
660
0
        column->insert_data(reinterpret_cast<const char*>(&t_expr.bool_literal.value), 0);
661
0
        break;
662
876
    }
663
64
    case TExprNodeType::NULL_LITERAL: {
664
        // insert a null literal
665
64
        if (!column->is_nullable()) {
666
            // https://github.com/apache/doris/pull/39449 have forbid this cause. always add this check as protective measures
667
0
            return Status::InternalError("The column {} is not null, can't insert into NULL value.",
668
0
                                         part_key->first->get_by_position(pos).name);
669
0
        }
670
64
        column->insert_data(nullptr, 0);
671
64
        break;
672
64
    }
673
0
    default: {
674
0
        return Status::InternalError("unsupported partition column node type, type={}",
675
0
                                     t_expr.node_type);
676
64
    }
677
3.83k
    }
678
3.86k
    part_key->second = cast_set<int32_t>(column->size() - 1);
679
3.86k
    return Status::OK();
680
3.83k
}
681
// NOLINTEND(readability-function-size)
682
683
Status VOlapTablePartitionParam::_create_partition_keys(const std::vector<TExprNode>& t_exprs,
684
3.78k
                                                        BlockRow* part_key) {
685
7.62k
    for (int i = 0; i < t_exprs.size(); i++) {
686
3.83k
        RETURN_IF_ERROR(_create_partition_key(t_exprs[i], part_key, _partition_slot_locs[i]));
687
3.83k
    }
688
3.78k
    return Status::OK();
689
3.78k
}
690
691
Status VOlapTablePartitionParam::generate_partition_from(const TOlapTablePartition& t_part,
692
6.68k
                                                         VOlapTablePartition*& part_result) {
693
6.68k
    DCHECK(part_result == nullptr);
694
    // here we set the default value of partition bounds first! if it doesn't have some key, it will be -1.
695
6.68k
    part_result = _obj_pool.add(new VOlapTablePartition(&_partition_block));
696
6.68k
    part_result->id = t_part.id;
697
6.68k
    part_result->is_mutable = t_part.is_mutable;
698
    // only load_to_single_tablet = true will set load_tablet_idx
699
6.68k
    if (t_part.__isset.load_tablet_idx) {
700
2.36k
        part_result->load_tablet_idx = t_part.load_tablet_idx;
701
2.36k
    }
702
703
6.68k
    if (_is_in_partition) {
704
1.88k
        for (const auto& keys : t_part.in_keys) {
705
1.85k
            RETURN_IF_ERROR(_create_partition_keys(
706
1.85k
                    keys, &part_result->in_keys.emplace_back(&_partition_block, -1)));
707
1.85k
        }
708
1.88k
        if (t_part.__isset.is_default_partition && t_part.is_default_partition &&
709
1.88k
            _default_partition == nullptr) {
710
0
            _default_partition = part_result;
711
0
        }
712
4.79k
    } else { // range
713
4.79k
        if (t_part.__isset.start_keys) {
714
949
            RETURN_IF_ERROR(_create_partition_keys(t_part.start_keys, &part_result->start_key));
715
949
        }
716
        // we generate the right bound but not insert into partition map
717
4.79k
        if (t_part.__isset.end_keys) {
718
973
            RETURN_IF_ERROR(_create_partition_keys(t_part.end_keys, &part_result->end_key));
719
973
        }
720
4.79k
    }
721
722
6.68k
    part_result->num_buckets = t_part.num_buckets;
723
6.68k
    auto num_indexes = _schema->indexes().size();
724
6.68k
    if (t_part.indexes.size() != num_indexes) {
725
0
        return Status::InternalError(
726
0
                "number of partition's index is not equal with schema's"
727
0
                ", num_part_indexes={}, num_schema_indexes={}",
728
0
                t_part.indexes.size(), num_indexes);
729
0
    }
730
6.68k
    part_result->indexes = t_part.indexes;
731
6.68k
    std::sort(part_result->indexes.begin(), part_result->indexes.end(),
732
6.68k
              [](const OlapTableIndexTablets& lhs, const OlapTableIndexTablets& rhs) {
733
0
                  return lhs.index_id < rhs.index_id;
734
0
              });
735
    // check index
736
13.4k
    for (int j = 0; j < num_indexes; ++j) {
737
6.73k
        if (part_result->indexes[j].index_id != _schema->indexes()[j]->index_id) {
738
0
            return Status::InternalError(
739
0
                    "partition's index is not equal with schema's"
740
0
                    ", part_index={}, schema_index={}",
741
0
                    part_result->indexes[j].index_id, _schema->indexes()[j]->index_id);
742
0
        }
743
6.73k
    }
744
6.71k
    if (t_part.__isset.total_replica_num) {
745
6.71k
        part_result->total_replica_num = t_part.total_replica_num;
746
6.71k
    }
747
6.71k
    if (t_part.__isset.load_required_replica_num) {
748
6.71k
        part_result->load_required_replica_num = t_part.load_required_replica_num;
749
6.71k
    }
750
6.68k
    if (t_part.__isset.tablet_version_gap_backends) {
751
0
        for (const auto& [tablet_id, backend_ids] : t_part.tablet_version_gap_backends) {
752
0
            auto& gap_set = part_result->tablet_version_gap_backends[tablet_id];
753
0
            for (auto backend_id : backend_ids) {
754
0
                gap_set.insert(backend_id);
755
0
            }
756
0
        }
757
0
    }
758
6.68k
    return Status::OK();
759
6.68k
}
760
761
Status VOlapTablePartitionParam::add_partitions(
762
8
        const std::vector<TOlapTablePartition>& partitions) {
763
8
    for (const auto& t_part : partitions) {
764
8
        auto* part = _obj_pool.add(new VOlapTablePartition(&_partition_block));
765
8
        part->id = t_part.id;
766
8
        part->is_mutable = t_part.is_mutable;
767
768
        // we dont pass right keys when it's MAX_VALUE. so there's possibility we only have start_key but not end_key
769
        // range partition
770
8
        if (t_part.__isset.start_keys) {
771
2
            RETURN_IF_ERROR(_create_partition_keys(t_part.start_keys, &part->start_key));
772
2
        }
773
8
        if (t_part.__isset.end_keys) {
774
2
            RETURN_IF_ERROR(_create_partition_keys(t_part.end_keys, &part->end_key));
775
2
        }
776
        // list partition - we only set 1 value in 1 partition for new created ones
777
8
        if (t_part.__isset.in_keys) {
778
6
            for (const auto& keys : t_part.in_keys) {
779
6
                RETURN_IF_ERROR(_create_partition_keys(
780
6
                        keys, &part->in_keys.emplace_back(&_partition_block, -1)));
781
6
            }
782
6
            if (t_part.__isset.is_default_partition && t_part.is_default_partition) {
783
0
                _default_partition = part;
784
0
            }
785
6
        }
786
787
8
        part->num_buckets = t_part.num_buckets;
788
8
        auto num_indexes = _schema->indexes().size();
789
8
        if (t_part.indexes.size() != num_indexes) {
790
0
            return Status::InternalError(
791
0
                    "number of partition's index is not equal with schema's"
792
0
                    ", num_part_indexes={}, num_schema_indexes={}",
793
0
                    t_part.indexes.size(), num_indexes);
794
0
        }
795
8
        part->indexes = t_part.indexes;
796
8
        std::sort(part->indexes.begin(), part->indexes.end(),
797
8
                  [](const OlapTableIndexTablets& lhs, const OlapTableIndexTablets& rhs) {
798
0
                      return lhs.index_id < rhs.index_id;
799
0
                  });
800
        // check index
801
16
        for (int j = 0; j < num_indexes; ++j) {
802
8
            if (part->indexes[j].index_id != _schema->indexes()[j]->index_id) {
803
0
                return Status::InternalError(
804
0
                        "partition's index is not equal with schema's"
805
0
                        ", part_index={}, schema_index={}",
806
0
                        part->indexes[j].index_id, _schema->indexes()[j]->index_id);
807
0
            }
808
8
        }
809
8
        _partitions.emplace_back(part);
810
        // after _creating_partiton_keys
811
8
        if (_is_in_partition) {
812
6
            for (auto& in_key : part->in_keys) {
813
6
                _partitions_map->emplace(std::tuple {in_key.first, in_key.second, false}, part);
814
6
            }
815
6
        } else {
816
2
            _partitions_map->emplace(std::tuple {part->end_key.first, part->end_key.second, false},
817
2
                                     part);
818
2
        }
819
8
    }
820
821
8
    return Status::OK();
822
8
}
823
824
Status VOlapTablePartitionParam::replace_partitions(
825
        std::vector<int64_t>& old_partition_ids,
826
1
        const std::vector<TOlapTablePartition>& new_partitions) {
827
    // remove old replaced partitions
828
1
    DCHECK(old_partition_ids.size() == new_partitions.size());
829
830
    // init and add new partitions. insert into _partitions
831
3
    for (int i = 0; i < new_partitions.size(); i++) {
832
2
        const auto& t_part = new_partitions[i];
833
        // pair old_partition_ids and new_partitions one by one. TODO: sort to opt performance
834
2
        VOlapTablePartition* old_part = nullptr;
835
2
        auto old_part_id = old_partition_ids[i];
836
2
        if (auto it = std::find_if(
837
2
                    _partitions.begin(), _partitions.end(),
838
3
                    [=](const VOlapTablePartition* lhs) { return lhs->id == old_part_id; });
839
2
            it != _partitions.end()) {
840
2
            old_part = *it;
841
2
        } else {
842
0
            return Status::InternalError("Cannot find old tablet {} in replacing", old_part_id);
843
0
        }
844
845
2
        auto* part = _obj_pool.add(new VOlapTablePartition(&_partition_block));
846
2
        part->id = t_part.id;
847
2
        part->is_mutable = t_part.is_mutable;
848
849
        /// just substitute directly. no need to remove and reinsert keys.
850
        // range partition
851
2
        part->start_key = std::move(old_part->start_key);
852
2
        part->end_key = std::move(old_part->end_key);
853
        // list partition
854
2
        part->in_keys = std::move(old_part->in_keys);
855
2
        if (t_part.__isset.is_default_partition && t_part.is_default_partition) {
856
0
            _default_partition = part;
857
0
        }
858
859
2
        part->num_buckets = t_part.num_buckets;
860
2
        auto num_indexes = _schema->indexes().size();
861
2
        if (t_part.indexes.size() != num_indexes) {
862
0
            return Status::InternalError(
863
0
                    "number of partition's index is not equal with schema's"
864
0
                    ", num_part_indexes={}, num_schema_indexes={}",
865
0
                    t_part.indexes.size(), num_indexes);
866
0
        }
867
2
        part->indexes = t_part.indexes;
868
2
        std::sort(part->indexes.begin(), part->indexes.end(),
869
2
                  [](const OlapTableIndexTablets& lhs, const OlapTableIndexTablets& rhs) {
870
0
                      return lhs.index_id < rhs.index_id;
871
0
                  });
872
        // check index
873
4
        for (int j = 0; j < num_indexes; ++j) {
874
2
            if (part->indexes[j].index_id != _schema->indexes()[j]->index_id) {
875
0
                return Status::InternalError(
876
0
                        "partition's index is not equal with schema's"
877
0
                        ", part_index={}, schema_index={}",
878
0
                        part->indexes[j].index_id, _schema->indexes()[j]->index_id);
879
0
            }
880
2
        }
881
882
        // add new partitions with new id.
883
2
        _partitions.emplace_back(part);
884
2
        VLOG_NOTICE << "params add new partition " << part->id;
885
886
        // replace items in _partition_maps
887
2
        if (_is_in_partition) {
888
0
            for (auto& in_key : part->in_keys) {
889
0
                (*_partitions_map)[std::tuple {in_key.first, in_key.second, false}] = part;
890
0
            }
891
2
        } else {
892
2
            (*_partitions_map)[std::tuple {part->end_key.first, part->end_key.second, false}] =
893
2
                    part;
894
2
        }
895
2
    }
896
    // remove old partitions by id
897
1
    std::ranges::sort(old_partition_ids);
898
5
    for (auto it = _partitions.begin(); it != _partitions.end();) {
899
4
        if (std::ranges::binary_search(old_partition_ids, (*it)->id)) {
900
2
            it = _partitions.erase(it);
901
2
        } else {
902
2
            it++;
903
2
        }
904
4
    }
905
906
1
    return Status::OK();
907
1
}
908
#include "common/compile_check_end.h"
909
910
} // namespace doris