Coverage Report

Created: 2025-12-30 16:20

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