Coverage Report

Created: 2026-07-17 16:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/tablet/tablet_schema.h
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
#pragma once
19
20
#include <gen_cpp/AgentService_types.h>
21
#include <gen_cpp/Types_types.h>
22
#include <gen_cpp/olap_common.pb.h>
23
#include <gen_cpp/olap_file.pb.h>
24
#include <gen_cpp/segment_v2.pb.h>
25
#include <parallel_hashmap/phmap.h>
26
27
#include <algorithm>
28
#include <cstdint>
29
#include <map>
30
#include <memory>
31
#include <string>
32
#include <unordered_map>
33
#include <unordered_set>
34
#include <utility>
35
#include <vector>
36
37
#include "common/consts.h"
38
#include "common/status.h"
39
#include "core/data_type/define_primitive_type.h"
40
#include "core/string_ref.h"
41
#include "core/types.h"
42
#include "exec/common/string_utils/string_utils.h"
43
#include "exprs/aggregate/aggregate_function.h"
44
#include "runtime/descriptors.h"
45
#include "runtime/memory/lru_cache_policy.h"
46
#include "storage/index/inverted/inverted_index_parser.h"
47
#include "storage/metadata_adder.h"
48
#include "storage/olap_common.h"
49
#include "storage/segment/options.h"
50
#include "util/debug_points.h"
51
#include "util/json/path_in_data.h"
52
#include "util/string_parser.hpp"
53
#include "util/string_util.h"
54
55
namespace doris {
56
class Block;
57
class PathInData;
58
class IDataType;
59
60
struct OlapTableIndexSchema;
61
class TColumn;
62
class TOlapTableIndex;
63
class TabletColumn;
64
65
using TabletColumnPtr = std::shared_ptr<TabletColumn>;
66
67
class TabletColumn : public MetadataAdder<TabletColumn> {
68
public:
69
    struct VariantParams {
70
        int32_t max_subcolumns_count = 0;
71
        bool enable_typed_paths_to_sparse = false;
72
        int32_t max_sparse_column_statistics_size =
73
                BeConsts::DEFAULT_VARIANT_MAX_SPARSE_COLUMN_STATS_SIZE;
74
        // default to 0, no shard
75
        int32_t sparse_hash_shard_count = 0;
76
77
        bool enable_doc_mode = false;
78
        int64_t doc_materialization_min_rows = 0;
79
        int32_t doc_hash_shard_count = 64;
80
81
        bool enable_nested_group = false;
82
    };
83
84
    TabletColumn();
85
    TabletColumn(const ColumnPB& column);
86
    TabletColumn(const TColumn& column);
87
    TabletColumn(FieldAggregationMethod agg, FieldType type);
88
    TabletColumn(FieldAggregationMethod agg, FieldType filed_type, bool is_nullable);
89
    TabletColumn(FieldAggregationMethod agg, FieldType filed_type, bool is_nullable,
90
                 int32_t unique_id, size_t length);
91
92
#ifdef BE_TEST
93
50.7k
    virtual ~TabletColumn() = default;
94
#endif
95
96
    void init_from_pb(const ColumnPB& column);
97
    void init_from_thrift(const TColumn& column);
98
    void to_schema_pb(ColumnPB* column) const;
99
100
189k
    int32_t unique_id() const { return _unique_id; }
101
2.17k
    void set_unique_id(int32_t id) { _unique_id = id; }
102
626k
    const std::string& name() const { return _col_name; }
103
23.5k
    const std::string& name_lower_case() const { return _col_name_lower_case; }
104
6.36k
    void set_name(std::string col_name) {
105
6.36k
        _col_name = col_name;
106
6.36k
        _col_name_lower_case = to_lower(_col_name);
107
6.36k
    }
108
2.62M
    MOCK_FUNCTION FieldType type() const { return _type; }
109
6.60k
    void set_type(FieldType type) { _type = type; }
110
91.2k
    bool is_key() const { return _is_key; }
111
121k
    bool is_nullable() const { return _is_nullable; }
112
0
    bool is_auto_increment() const { return _is_auto_increment; }
113
0
    bool is_seqeunce_col() const { return _col_name == SEQUENCE_COL; }
114
0
    bool is_on_update_current_timestamp() const { return _is_on_update_current_timestamp; }
115
77.3k
    bool is_variant_type() const { return _type == FieldType::OLAP_FIELD_TYPE_VARIANT; }
116
13.9k
    bool is_bf_column() const { return _is_bf_column; }
117
36.0k
    bool is_array_type() const { return _type == FieldType::OLAP_FIELD_TYPE_ARRAY; }
118
7.13k
    bool is_agg_state_type() const { return _type == FieldType::OLAP_FIELD_TYPE_AGG_STATE; }
119
0
    bool is_jsonb_type() const { return _type == FieldType::OLAP_FIELD_TYPE_JSONB; }
120
153
    bool is_length_variable_type() const {
121
153
        return _type == FieldType::OLAP_FIELD_TYPE_CHAR ||
122
153
               _type == FieldType::OLAP_FIELD_TYPE_VARCHAR ||
123
153
               _type == FieldType::OLAP_FIELD_TYPE_STRING ||
124
153
               _type == FieldType::OLAP_FIELD_TYPE_HLL ||
125
153
               _type == FieldType::OLAP_FIELD_TYPE_BITMAP ||
126
153
               _type == FieldType::OLAP_FIELD_TYPE_QUANTILE_STATE ||
127
153
               _type == FieldType::OLAP_FIELD_TYPE_AGG_STATE;
128
153
    }
129
    // Such columns are not exist in frontend schema info, so we need to
130
    // add them into tablet_schema for later column indexing.
131
    static TabletColumn create_materialized_variant_column(const std::string& root,
132
                                                           const std::vector<std::string>& paths,
133
                                                           int32_t parent_unique_id,
134
                                                           int32_t max_subcolumns_count,
135
                                                           bool enable_doc_mode = false);
136
37
    bool has_default_value() const { return _has_default_value; }
137
13.3k
    std::string default_value() const { return _default_value; }
138
100k
    int32_t length() const { return _length; }
139
3.06k
    void set_length(int32_t length) { _length = length; }
140
889
    void set_default_value(const std::string& default_value) {
141
889
        _default_value = default_value;
142
889
        _has_default_value = true;
143
889
    }
144
2.25k
    int32_t index_length() const { return _index_length; }
145
2.33k
    void set_index_length(int32_t index_length) { _index_length = index_length; }
146
1.90k
    void set_is_key(bool is_key) { _is_key = is_key; }
147
3.35k
    void set_is_nullable(bool is_nullable) { _is_nullable = is_nullable; }
148
0
    void set_is_auto_increment(bool is_auto_increment) { _is_auto_increment = is_auto_increment; }
149
0
    void set_is_on_update_current_timestamp(bool is_on_update_current_timestamp) {
150
0
        _is_on_update_current_timestamp = is_on_update_current_timestamp;
151
0
    }
152
    void set_path_info(const PathInData& path);
153
2.39k
    FieldAggregationMethod aggregation() const { return _aggregation; }
154
    AggregateFunctionPtr get_aggregate_function_union(DataTypePtr type,
155
                                                      int current_be_exec_version) const;
156
    AggregateFunctionPtr get_aggregate_function(std::string suffix,
157
                                                int current_be_exec_version) const;
158
100k
    int precision() const { return _precision; }
159
101k
    int frac() const { return _frac; }
160
33
    inline bool visible() const { return _visible; }
161
    bool has_char_type() const;
162
163
2.40k
    void set_aggregation_method(FieldAggregationMethod agg) {
164
2.40k
        _aggregation = agg;
165
2.40k
        _aggregation_name = get_string_by_aggregation_type(agg);
166
2.40k
    }
167
168
    /**
169
     * Add a sub column.
170
     */
171
    void add_sub_column(TabletColumn& sub_column);
172
173
23.6k
    uint32_t get_subtype_count() const { return _sub_column_count; }
174
3.98k
    MOCK_FUNCTION const TabletColumn& get_sub_column(uint64_t i) const { return *_sub_columns[i]; }
175
4.57k
    const std::vector<TabletColumnPtr>& get_sub_columns() const { return _sub_columns; }
176
177
    friend bool operator==(const TabletColumn& a, const TabletColumn& b);
178
    friend bool operator!=(const TabletColumn& a, const TabletColumn& b);
179
180
    static std::string get_string_by_field_type(FieldType type);
181
    static std::string get_string_by_aggregation_type(FieldAggregationMethod aggregation_type);
182
    static FieldType get_field_type_by_string(const std::string& str);
183
    static FieldAggregationMethod get_aggregation_type_by_string(const std::string& str);
184
    static uint32_t get_field_length_by_type(TPrimitiveType::type type, uint32_t string_length);
185
    bool is_row_store_column() const;
186
10.8k
    std::string get_aggregation_name() const { return _aggregation_name; }
187
10.8k
    bool get_result_is_nullable() const { return _result_is_nullable; }
188
10.8k
    int get_be_exec_version() const { return _be_exec_version; }
189
61.3k
    bool has_path_info() const { return _column_path != nullptr && !_column_path->empty(); }
190
18.3k
    const PathInDataPtr& path_info_ptr() const { return _column_path; }
191
    // If it is an extracted column from variant column
192
139k
    bool is_extracted_column() const {
193
139k
        return _column_path != nullptr && !_column_path->empty() && _parent_col_unique_id >= 0;
194
139k
    };
195
17.8k
    std::string suffix_path() const {
196
17.8k
        return is_extracted_column() ? _column_path->get_path() : "";
197
17.8k
    }
198
127
    bool is_nested_subcolumn() const {
199
127
        return _column_path != nullptr && _column_path->has_nested_part();
200
127
    }
201
7.06k
    int32_t parent_unique_id() const { return _parent_col_unique_id; }
202
2.74k
    void set_parent_unique_id(int32_t col_unique_id) { _parent_col_unique_id = col_unique_id; }
203
1.20k
    void set_is_bf_column(bool is_bf_column) { _is_bf_column = is_bf_column; }
204
    std::shared_ptr<const IDataType> get_vec_type() const;
205
206
922
    Status check_valid() const {
207
922
        if (type() != FieldType::OLAP_FIELD_TYPE_ARRAY &&
208
922
            type() != FieldType::OLAP_FIELD_TYPE_STRUCT &&
209
922
            type() != FieldType::OLAP_FIELD_TYPE_MAP) {
210
922
            return Status::OK();
211
922
        }
212
0
        if (is_bf_column()) {
213
0
            return Status::NotSupported("Do not support bloom filter index, type={}",
214
0
                                        get_string_by_field_type(type()));
215
0
        }
216
0
        return Status::OK();
217
0
    }
218
219
8
    void set_precision(int precision) {
220
8
        _precision = precision;
221
8
        _is_decimal = true;
222
8
    }
223
224
249
    void set_frac(int frac) { _frac = frac; }
225
226
0
    const VariantParams& variant_params() const { return _variant; }
227
0
    VariantParams* mutable_variant_params() { return &_variant; }
228
229
3.50k
    int32_t variant_max_subcolumns_count() const { return _variant.max_subcolumns_count; }
230
231
93
    void set_variant_max_subcolumns_count(int32_t variant_max_subcolumns_count) {
232
93
        _variant.max_subcolumns_count = variant_max_subcolumns_count;
233
93
    }
234
235
405
    PatternTypePB pattern_type() const { return _pattern_type; }
236
237
798
    bool variant_enable_typed_paths_to_sparse() const {
238
798
        return _variant.enable_typed_paths_to_sparse;
239
798
    }
240
241
21.3k
    int32_t variant_max_sparse_column_statistics_size() const {
242
21.3k
        return _variant.max_sparse_column_statistics_size;
243
21.3k
    }
244
245
501
    int32_t variant_sparse_hash_shard_count() const { return _variant.sparse_hash_shard_count; }
246
247
4.83k
    bool variant_enable_doc_mode() const { return _variant.enable_doc_mode; }
248
249
21
    int64_t variant_doc_materialization_min_rows() const {
250
21
        return _variant.doc_materialization_min_rows;
251
21
    }
252
253
18
    int32_t variant_doc_hash_shard_count() const { return _variant.doc_hash_shard_count; }
254
255
9
    void set_variant_doc_materialization_min_rows(int64_t variant_doc_materialization_min_rows) {
256
9
        _variant.doc_materialization_min_rows = variant_doc_materialization_min_rows;
257
9
    }
258
259
9
    void set_variant_doc_hash_shard_count(int32_t variant_doc_hash_shard_count) {
260
9
        _variant.doc_hash_shard_count = variant_doc_hash_shard_count;
261
9
    }
262
263
    void set_variant_max_sparse_column_statistics_size(
264
11
            int32_t variant_max_sparse_column_statistics_size) {
265
11
        _variant.max_sparse_column_statistics_size = variant_max_sparse_column_statistics_size;
266
11
    }
267
268
9
    void set_variant_sparse_hash_shard_count(int32_t variant_sparse_hash_shard_count) {
269
9
        _variant.sparse_hash_shard_count = variant_sparse_hash_shard_count;
270
9
    }
271
272
36
    void set_variant_enable_doc_mode(bool variant_enable_doc_mode) {
273
36
        _variant.enable_doc_mode = variant_enable_doc_mode;
274
36
    }
275
276
1
    void set_variant_enable_typed_paths_to_sparse(bool variant_enable_typed_paths_to_sparse) {
277
1
        _variant.enable_typed_paths_to_sparse = variant_enable_typed_paths_to_sparse;
278
1
    }
279
280
4.95k
    bool variant_enable_nested_group() const { return _variant.enable_nested_group; }
281
282
10
    void set_variant_enable_nested_group(bool val) { _variant.enable_nested_group = val; }
283
284
241
    bool is_decimal() const { return _is_decimal; }
285
286
private:
287
    int32_t _unique_id = -1;
288
    std::string _col_name;
289
    std::string _col_name_lower_case;
290
    // the field _type will change from TPrimitiveType
291
    // to string by 'EnumToString(TPrimitiveType, tcolumn.column_type.type, data_type);' (reference: TabletMeta::init_column_from_tcolumn)
292
    // to FieldType by 'TabletColumn::get_field_type_by_string' (reference: TabletColumn::init_from_pb).
293
    // And the _type in columnPB is string and it changed from FieldType by 'get_string_by_field_type' (reference: TabletColumn::to_schema_pb).
294
    FieldType _type;
295
    bool _is_key = false;
296
    FieldAggregationMethod _aggregation;
297
    std::string _aggregation_name;
298
    bool _is_nullable = false;
299
    bool _is_auto_increment = false;
300
    bool _is_on_update_current_timestamp {false};
301
302
    bool _has_default_value = false;
303
    std::string _default_value;
304
305
    bool _is_decimal = false;
306
    int32_t _precision = -1;
307
    int32_t _frac = -1;
308
309
    int32_t _length = -1;
310
    int32_t _index_length = -1;
311
312
    bool _is_bf_column = false;
313
314
    bool _visible = true;
315
316
    std::vector<TabletColumnPtr> _sub_columns;
317
    uint32_t _sub_column_count = 0;
318
319
    bool _result_is_nullable = false;
320
    int _be_exec_version = -1;
321
322
    // The extracted sub-columns from "variant" contain the following information:
323
    int32_t _parent_col_unique_id = -1; // "variant" -> col_unique_id
324
    PathInDataPtr _column_path;         // the path of the sub-columns themselves
325
    PatternTypePB _pattern_type = PatternTypePB::MATCH_NAME_GLOB;
326
327
    VariantParams _variant;
328
};
329
330
bool operator==(const TabletColumn& a, const TabletColumn& b);
331
bool operator!=(const TabletColumn& a, const TabletColumn& b);
332
333
class TabletIndex : public MetadataAdder<TabletIndex> {
334
public:
335
7.96k
    TabletIndex() = default;
336
    void init_from_thrift(const TOlapTableIndex& index, const TabletSchema& tablet_schema);
337
    void init_from_thrift(const TOlapTableIndex& index, const std::vector<int32_t>& column_uids);
338
    void init_from_pb(const TabletIndexPB& index);
339
    void to_schema_pb(TabletIndexPB* index) const;
340
341
20.7k
    int64_t index_id() const { return _index_id; }
342
33
    const std::string& index_name() const { return _index_name; }
343
15.3k
    MOCK_FUNCTION IndexType index_type() const { return _index_type; }
344
10.3k
    const std::vector<int32_t>& col_unique_ids() const { return _col_unique_ids; }
345
27.5k
    MOCK_FUNCTION const std::map<std::string, std::string>& properties() const {
346
27.5k
        return _properties;
347
27.5k
    }
348
1
    int32_t get_gram_size() const {
349
1
        if (_properties.contains("gram_size")) {
350
1
            return std::stoi(_properties.at("gram_size"));
351
1
        }
352
353
0
        return 0;
354
1
    }
355
1
    int32_t get_gram_bf_size() const {
356
1
        if (_properties.contains("bf_size")) {
357
1
            return std::stoi(_properties.at("bf_size"));
358
1
        }
359
360
0
        return 0;
361
1
    }
362
363
19.7k
    const std::string& get_index_suffix() const { return _escaped_index_suffix_path; }
364
365
    void set_escaped_escaped_index_suffix_path(const std::string& name);
366
367
2.39k
    bool is_inverted_index() const { return _index_type == IndexType::INVERTED; }
368
369
2
    bool is_ann_index() const { return _index_type == IndexType::ANN; }
370
371
14
    void remove_parser_and_analyzer() {
372
14
        _properties.erase(INVERTED_INDEX_PARSER_KEY);
373
14
        _properties.erase(INVERTED_INDEX_PARSER_KEY_ALIAS);
374
14
        _properties.erase(INVERTED_INDEX_ANALYZER_NAME_KEY);
375
14
        _properties.erase(INVERTED_INDEX_NORMALIZER_NAME_KEY);
376
14
    }
377
378
7.90k
    std::string field_pattern() const {
379
7.90k
        if (_properties.contains("field_pattern")) {
380
331
            return _properties.at("field_pattern");
381
331
        }
382
7.57k
        return "";
383
7.90k
    }
384
385
8
    bool is_same_except_id(const TabletIndex* other) const {
386
8
        return _escaped_index_suffix_path == other->_escaped_index_suffix_path &&
387
8
               _index_name == other->_index_name && _index_type == other->_index_type &&
388
8
               _col_unique_ids == other->_col_unique_ids && _properties == other->_properties;
389
8
    }
390
391
private:
392
    int64_t _index_id = -1;
393
    // Identify the different index with the same _index_id
394
    std::string _escaped_index_suffix_path;
395
    std::string _index_name;
396
    IndexType _index_type;
397
    std::vector<int32_t> _col_unique_ids;
398
    std::map<std::string, std::string> _properties;
399
};
400
401
using TabletIndexPtr = std::shared_ptr<TabletIndex>;
402
using TabletIndexes = std::vector<std::shared_ptr<TabletIndex>>;
403
using PathSet = phmap::flat_hash_set<std::string>;
404
405
class TabletSchema : public MetadataAdder<TabletSchema> {
406
public:
407
    enum class ColumnType { NORMAL = 0, DROPPED = 1, VARIANT = 2 };
408
    // TODO(yingchun): better to make constructor as private to avoid
409
    // manually init members incorrectly, and define a new function like
410
    // void create_from_pb(const TabletSchemaPB& schema, TabletSchema* tablet_schema).
411
    TabletSchema();
412
    ~TabletSchema() override;
413
414
    // Init from pb
415
    // ignore_extracted_columns: ignore the extracted columns from variant column
416
    // reuse_cached_column: reuse the cached column in the schema if they are the same, to reduce memory usage
417
    void init_from_pb(const TabletSchemaPB& schema, bool ignore_extracted_columns = false,
418
                      bool reuse_cached_column = false);
419
    // Notice: Use deterministic way to serialize protobuf,
420
    // since serialize Map in protobuf may could lead to un-deterministic by default
421
    template <class PbType>
422
7.72k
    static std::string deterministic_string_serialize(const PbType& pb) {
423
7.72k
        std::string output;
424
7.72k
        google::protobuf::io::StringOutputStream string_output_stream(&output);
425
7.72k
        google::protobuf::io::CodedOutputStream output_stream(&string_output_stream);
426
7.72k
        output_stream.SetSerializationDeterministic(true);
427
7.72k
        pb.SerializeToCodedStream(&output_stream);
428
7.72k
        return output;
429
7.72k
    }
_ZN5doris12TabletSchema30deterministic_string_serializeINS_14TabletSchemaPBEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Line
Count
Source
422
6.79k
    static std::string deterministic_string_serialize(const PbType& pb) {
423
6.79k
        std::string output;
424
6.79k
        google::protobuf::io::StringOutputStream string_output_stream(&output);
425
6.79k
        google::protobuf::io::CodedOutputStream output_stream(&string_output_stream);
426
6.79k
        output_stream.SetSerializationDeterministic(true);
427
6.79k
        pb.SerializeToCodedStream(&output_stream);
428
6.79k
        return output;
429
6.79k
    }
_ZN5doris12TabletSchema30deterministic_string_serializeINS_8ColumnPBEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Line
Count
Source
422
674
    static std::string deterministic_string_serialize(const PbType& pb) {
423
674
        std::string output;
424
674
        google::protobuf::io::StringOutputStream string_output_stream(&output);
425
674
        google::protobuf::io::CodedOutputStream output_stream(&string_output_stream);
426
674
        output_stream.SetSerializationDeterministic(true);
427
674
        pb.SerializeToCodedStream(&output_stream);
428
674
        return output;
429
674
    }
_ZN5doris12TabletSchema30deterministic_string_serializeINS_13TabletIndexPBEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Line
Count
Source
422
232
    static std::string deterministic_string_serialize(const PbType& pb) {
423
232
        std::string output;
424
232
        google::protobuf::io::StringOutputStream string_output_stream(&output);
425
232
        google::protobuf::io::CodedOutputStream output_stream(&string_output_stream);
426
232
        output_stream.SetSerializationDeterministic(true);
427
232
        pb.SerializeToCodedStream(&output_stream);
428
232
        return output;
429
232
    }
_ZN5doris12TabletSchema30deterministic_string_serializeINS_21POlapTableIndexSchemaEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Line
Count
Source
422
21
    static std::string deterministic_string_serialize(const PbType& pb) {
423
21
        std::string output;
424
21
        google::protobuf::io::StringOutputStream string_output_stream(&output);
425
21
        google::protobuf::io::CodedOutputStream output_stream(&string_output_stream);
426
21
        output_stream.SetSerializationDeterministic(true);
427
21
        pb.SerializeToCodedStream(&output_stream);
428
21
        return output;
429
21
    }
430
    void to_schema_pb(TabletSchemaPB* tablet_meta_pb) const;
431
    void append_column(TabletColumn column, ColumnType col_type = ColumnType::NORMAL);
432
    void append_index(TabletIndex&& index);
433
    void remove_index(int64_t index_id);
434
    void clear_index();
435
    // Must make sure the row column is always the last column
436
    void add_row_column();
437
    void copy_from(const TabletSchema& tablet_schema);
438
    // lightweight copy, take care of lifecycle of TabletColumn
439
    void shawdow_copy_without_columns(const TabletSchema& tablet_schema);
440
    void update_index_info_from(const TabletSchema& tablet_schema);
441
    std::string to_key() const;
442
    // get_metadata_size is only the memory of the TabletSchema itself, not include child objects.
443
192
    int64_t mem_size() const { return get_metadata_size(); }
444
    size_t row_size() const;
445
    int32_t field_index(const std::string& field_name) const;
446
    int32_t field_index(const PathInData& path) const;
447
    int32_t field_index(int32_t col_unique_id) const;
448
    const TabletColumn& column(size_t ordinal) const;
449
    Result<const TabletColumn*> column(const std::string& field_name) const;
450
    Status have_column(const std::string& field_name) const;
451
    bool exist_column(const std::string& field_name) const;
452
    bool has_column_unique_id(int32_t col_unique_id) const;
453
    const TabletColumn& column_by_uid(int32_t col_unique_id) const;
454
    TabletColumn& mutable_column_by_uid(int32_t col_unique_id);
455
    TabletColumn& mutable_column(size_t ordinal);
456
    void replace_column(size_t pos, TabletColumn new_col);
457
    const std::vector<TabletColumnPtr>& columns() const;
458
800k
    size_t num_columns() const { return _num_columns; }
459
0
    size_t num_visible_columns() const {
460
0
        return std::count_if(_cols.begin(), _cols.end(),
461
0
                             [](const TabletColumnPtr& column) { return column->visible(); });
462
0
    }
463
0
    size_t num_visible_value_columns() const {
464
0
        return std::count_if(_cols.begin(), _cols.end(), [](const TabletColumnPtr& column) {
465
0
            return column->visible() && !column->is_key();
466
0
        });
467
0
    }
468
    // num_key_columns: Total number of sort key columns in the table, determined by the key columns
469
    // specified in DUPLICATE KEY/UNIQUE KEY/AGGREGATE KEY when creating the table, used for complete data sorting
470
    // Example: CREATE TABLE t(a INT, b DATE, c VARCHAR) DUPLICATE KEY(a, b, c)
471
    //          Then num_key_columns = 3 (columns a, b, c are all sort keys)
472
1.07M
    size_t num_key_columns() const { return _num_key_columns; }
473
134k
    const std::vector<uint32_t>& cluster_key_uids() const { return _cluster_key_uids; }
474
0
    size_t num_null_columns() const { return _num_null_columns; }
475
    // num_short_key_columns: Number of columns used to build the Short Key Index, automatically calculated by FE
476
    // Limited by max column count (default 3) and max bytes (default 36 bytes). Types like float/double/STRING/JSONB
477
    // cannot be used as short keys. VARCHAR can only be the last short key column. Optimizes index size and query performance.
478
    // Example: CREATE TABLE t(a INT, b DATE, c VARCHAR) DUPLICATE KEY(a, b, c)
479
    //          Then num_short_key_columns = 3 (a, b, c all meet criteria, c as VARCHAR is the last short key)
480
    // Example: CREATE TABLE t(a INT, b DOUBLE, c DATE) DUPLICATE KEY(a, b, c)
481
    //          Then num_short_key_columns = 1 (b is DOUBLE type which cannot be short key, stops at b)
482
    // short key's size is limited to 36 bytes, because it will be loaded to memory during segment loaded.
483
2.70k
    size_t num_short_key_columns() const { return _num_short_key_columns; }
484
2
    size_t num_rows_per_row_block() const { return _num_rows_per_row_block; }
485
4.87k
    size_t num_variant_columns() const { return _num_variant_columns; };
486
0
    size_t num_virtual_columns() const { return _num_virtual_columns; }
487
7.10M
    KeysType keys_type() const { return _keys_type; }
488
3.03k
    SortType sort_type() const { return _sort_type; }
489
2
    size_t sort_col_num() const { return _sort_col_num; }
490
2
    CompressKind compress_kind() const { return _compress_kind; }
491
3
    size_t next_column_unique_id() const { return _next_column_unique_id; }
492
6
    bool has_bf_fpp() const { return _has_bf_fpp; }
493
4
    double bloom_filter_fpp() const { return _bf_fpp; }
494
8.58k
    bool is_in_memory() const { return _is_in_memory; }
495
0
    void set_is_in_memory(bool is_in_memory) { _is_in_memory = is_in_memory; }
496
5
    void set_disable_auto_compaction(bool disable_auto_compaction) {
497
5
        _disable_auto_compaction = disable_auto_compaction;
498
5
    }
499
167
    bool disable_auto_compaction() const { return _disable_auto_compaction; }
500
    // Deprecated legacy switch for flatten-nested variant behavior.
501
    // It is distinct from variant_enable_nested_group.
502
0
    void set_deprecated_variant_flatten_nested(bool flatten_nested) {
503
0
        _deprecated_enable_variant_flatten_nested = flatten_nested;
504
0
    }
505
372
    bool deprecated_variant_flatten_nested() const {
506
372
        return _deprecated_enable_variant_flatten_nested;
507
372
    }
508
    // indicate if full row store column(all the columns encodes as row) exists
509
1
    bool has_row_store_for_all_columns() const {
510
1
        return _store_row_column && row_columns_uids().empty();
511
1
    }
512
0
    void set_skip_write_index_on_load(bool skip) { _skip_write_index_on_load = skip; }
513
333
    bool skip_write_index_on_load() const { return _skip_write_index_on_load; }
514
4.46k
    int32_t delete_sign_idx() const { return _delete_sign_idx; }
515
160k
    bool has_sequence_col() const { return _sequence_col_idx != -1; }
516
64.7k
    int32_t sequence_col_idx() const { return _sequence_col_idx; }
517
0
    void set_version_col_idx(int32_t version_col_idx) { _version_col_idx = version_col_idx; }
518
0
    int32_t version_col_idx() const { return _version_col_idx; }
519
0
    bool has_skip_bitmap_col() const { return _skip_bitmap_col_idx != -1; }
520
0
    int32_t skip_bitmap_col_idx() const { return _skip_bitmap_col_idx; }
521
4
    int32_t commit_tso_col_idx() const { return _commit_tso_col_idx; }
522
1.47k
    int32_t binlog_tso_col_idx() const { return _binlog_tso_col_idx; }
523
4
    int32_t binlog_lsn_col_idx() const { return _binlog_lsn_col_idx; }
524
3
    int32_t binlog_op_col_idx() const { return _binlog_op_col_idx; }
525
2.56k
    segment_v2::CompressionTypePB compression_type() const { return _compression_type; }
526
0
    void set_row_store_page_size(long page_size) { _row_store_page_size = page_size; }
527
3
    long row_store_page_size() const { return _row_store_page_size; }
528
7
    void set_storage_page_size(long storage_page_size) { _storage_page_size = storage_page_size; }
529
10.6k
    long storage_page_size() const { return _storage_page_size; }
530
0
    void set_storage_dict_page_size(long storage_dict_page_size) {
531
0
        _storage_dict_page_size = storage_dict_page_size;
532
0
    }
533
10.6k
    long storage_dict_page_size() const { return _storage_dict_page_size; }
534
0
    bool has_global_row_id() const {
535
0
        for (auto [col_name, _] : _field_name_to_index) {
536
0
            if (col_name.start_with(StringRef(BeConsts::GLOBAL_ROWID_COL.data(),
537
0
                                              BeConsts::GLOBAL_ROWID_COL.size()))) {
538
0
                return true;
539
0
            }
540
0
        }
541
0
        return false;
542
0
    }
543
544
123
    const std::vector<const TabletIndex*> inverted_indexes() const {
545
123
        std::vector<const TabletIndex*> inverted_indexes;
546
1.26k
        for (const auto& index : _indexes) {
547
1.26k
            if (index->index_type() == IndexType::INVERTED) {
548
1.26k
                inverted_indexes.emplace_back(index.get());
549
1.26k
            }
550
1.26k
        }
551
123
        return inverted_indexes;
552
123
    }
553
6.95k
    bool has_inverted_index() const {
554
6.95k
        for (const auto& index : _indexes) {
555
1.07k
            DBUG_EXECUTE_IF("tablet_schema::has_inverted_index", {
556
1.07k
                if (index->col_unique_ids().empty()) {
557
1.07k
                    throw Exception(Status::InternalError("col unique ids cannot be empty"));
558
1.07k
                }
559
1.07k
            });
560
561
1.07k
            if (index->index_type() == IndexType::INVERTED) {
562
                //if index_id == -1, ignore it.
563
1.07k
                if (!index->col_unique_ids().empty() && index->col_unique_ids()[0] >= 0) {
564
1.07k
                    return true;
565
1.07k
                }
566
1.07k
            }
567
1.07k
        }
568
5.87k
        return false;
569
6.95k
    }
570
571
5.24k
    bool has_ann_index() const {
572
5.24k
        for (const auto& index : _indexes) {
573
7
            if (index->index_type() == IndexType::ANN) {
574
5
                if (!index->col_unique_ids().empty() && index->col_unique_ids()[0] >= 0) {
575
5
                    return true;
576
5
                }
577
5
            }
578
7
        }
579
5.24k
        return false;
580
5.24k
    }
581
582
    bool has_inverted_index_with_index_id(int64_t index_id) const;
583
584
    std::vector<const TabletIndex*> inverted_indexs(const TabletColumn& col) const;
585
586
    std::vector<const TabletIndex*> inverted_indexs(int32_t col_unique_id,
587
                                                    const std::string& suffix_path = "") const;
588
    const TabletIndex* ann_index(const TabletColumn& col) const;
589
590
    // Regardless of whether this column supports inverted index
591
    // TabletIndex information will be returned as long as it exists.
592
    const TabletIndex* ann_index(int32_t col_unique_id, const std::string& suffix_path = "") const;
593
594
    std::vector<TabletIndexPtr> inverted_index_by_field_pattern(
595
            int32_t col_unique_id, const std::string& field_pattern) const;
596
597
    bool has_ngram_bf_index(int32_t col_unique_id) const;
598
    const TabletIndex* get_ngram_bf_index(int32_t col_unique_id) const;
599
    const TabletIndex* get_index(int32_t col_unique_id, IndexType index_type,
600
                                 const std::string& suffix_path) const;
601
    void update_indexes_from_thrift(const std::vector<doris::TOlapTableIndex>& indexes);
602
    // If schema version is not set, it should be -1
603
7.38k
    int32_t schema_version() const { return _schema_version; }
604
    void clear_columns();
605
    Block create_block(
606
            const std::vector<uint32_t>& return_columns,
607
            const std::unordered_set<uint32_t>* tablet_columns_need_convert_null = nullptr) const;
608
    Block create_block() const;
609
4
    void set_schema_version(int32_t version) { _schema_version = version; }
610
0
    void set_auto_increment_column(const std::string& auto_increment_column) {
611
0
        _auto_increment_column = auto_increment_column;
612
0
    }
613
2
    std::string auto_increment_column() const { return _auto_increment_column; }
614
615
10
    void set_table_id(int64_t table_id) { _table_id = table_id; }
616
905
    int64_t table_id() const { return _table_id; }
617
10
    void set_db_id(int64_t db_id) { _db_id = db_id; }
618
325
    int64_t db_id() const { return _db_id; }
619
    void build_current_tablet_schema(int64_t index_id, int32_t version,
620
                                     const OlapTableIndexSchema* index,
621
                                     const TabletSchema& out_tablet_schema);
622
623
    // Merge columns that not exit in current schema, these column is dropped in current schema
624
    // but they are useful in some cases. For example,
625
    // 1. origin schema is  ColA, ColB
626
    // 2. insert values     1, 2
627
    // 3. delete where ColB = 2
628
    // 4. drop ColB
629
    // 5. insert values  3
630
    // 6. add column ColB, although it is name ColB, but it is different with previous ColB, the new ColB we name could call ColB'
631
    // 7. insert value  4, 5
632
    // Then the read schema should be ColA, ColB, ColB' because the delete predicate need ColB to remove related data.
633
    // Because they have same name, so that the dropped column should not be added to the map, only with unique id.
634
    void merge_dropped_columns(const TabletSchema& src_schema);
635
636
    bool is_dropped_column(const TabletColumn& col) const;
637
638
    // copy extracted columns from src_schema
639
    void copy_extracted_columns(const TabletSchema& src_schema);
640
641
    // only reserve extracted columns
642
    void reserve_extracted_columns();
643
644
4.04k
    std::string get_all_field_names() const {
645
4.04k
        std::string str = "[";
646
4.04k
        for (auto p : _field_name_to_index) {
647
4.04k
            if (str.size() > 1) {
648
0
                str += ", ";
649
0
            }
650
4.04k
            str += p.first.to_string() + "(" + std::to_string(_cols[p.second]->unique_id()) + ")";
651
4.04k
        }
652
4.04k
        str += "]";
653
4.04k
        return str;
654
4.04k
    }
655
656
    // Dump [(name, type, is_nullable), ...]
657
1
    std::string dump_structure() const {
658
1
        std::string str = "[";
659
15
        for (auto p : _cols) {
660
15
            if (str.size() > 1) {
661
14
                str += ", ";
662
14
            }
663
15
            str += "(";
664
15
            str += p->name();
665
15
            str += ", ";
666
15
            str += TabletColumn::get_string_by_field_type(p->type());
667
15
            str += ", ";
668
15
            str += "is_nullable:";
669
15
            str += (p->is_nullable() ? "true" : "false");
670
15
            str += ")";
671
15
        }
672
1
        str += "]";
673
1
        return str;
674
1
    }
675
676
1
    std::string dump_full_schema() const {
677
1
        std::string str = "[";
678
4
        for (auto p : _cols) {
679
4
            if (str.size() > 1) {
680
3
                str += ", ";
681
3
            }
682
4
            ColumnPB col_pb;
683
4
            p->to_schema_pb(&col_pb);
684
4
            str += "(";
685
4
            str += col_pb.ShortDebugString();
686
4
            str += ")";
687
4
        }
688
1
        str += "]";
689
1
        return str;
690
1
    }
691
692
    Block create_block_by_cids(const std::vector<uint32_t>& cids) const;
693
694
    std::shared_ptr<TabletSchema> copy_without_variant_extracted_columns();
695
7.21k
    InvertedIndexStorageFormatPB get_inverted_index_storage_format() const {
696
7.21k
        return _inverted_index_storage_format;
697
7.21k
    }
698
699
    void update_tablet_columns(const TabletSchema& tablet_schema,
700
                               const std::vector<TColumn>& t_columns);
701
702
4
    const std::vector<int32_t>& row_columns_uids() const { return _row_store_column_unique_ids; }
703
704
    int64_t get_metadata_size() const override;
705
706
    struct SubColumnInfo {
707
        TabletColumn column;
708
        TabletIndexes indexes;
709
    };
710
711
    // all path in path_set_info are relative to the parent column
712
    struct PathsSetInfo {
713
        std::unordered_map<std::string, SubColumnInfo> typed_path_set;    // typed columns
714
        std::unordered_map<std::string, TabletIndexes> subcolumn_indexes; // subcolumns indexes
715
        PathSet sub_path_set;                                             // extracted columns
716
        PathSet sparse_path_set;                                          // sparse columns
717
718
        // "Materialized regular path" means compaction chose to store this path as a dedicated
719
        // column in the schema, either typed or extracted, instead of re-emitting it dynamically.
720
0
        bool contains_materialized_regular_path(const std::string& path) const {
721
0
            return typed_path_set.contains(path) || sub_path_set.contains(path);
722
0
        }
723
    };
724
725
71
    void set_path_set_info(std::unordered_map<int32_t, PathsSetInfo>&& path_set_info_map) {
726
71
        _path_set_info_map = std::move(path_set_info_map);
727
71
    }
728
729
56
    const PathsSetInfo& path_set_info(int32_t unique_id) const {
730
56
        return _path_set_info_map.at(unique_id);
731
56
    }
732
733
7
    const PathsSetInfo* try_path_set_info(int32_t unique_id) const {
734
7
        auto it = _path_set_info_map.find(unique_id);
735
7
        return it == _path_set_info_map.end() ? nullptr : &it->second;
736
7
    }
737
738
6
    bool need_record_variant_extended_schema() const { return variant_max_subcolumns_count() == 0; }
739
740
11
    int32_t variant_max_subcolumns_count() const {
741
12
        for (const auto& col : _cols) {
742
12
            if (col->is_variant_type()) {
743
7
                return col->variant_max_subcolumns_count();
744
7
            }
745
12
        }
746
4
        return 0;
747
11
    }
748
    const std::unordered_map<uint32_t, std::vector<uint32_t>>& seq_col_idx_to_value_cols_idx()
749
0
            const {
750
0
        return _seq_col_idx_to_value_cols_idx;
751
0
    }
752
753
641
    bool has_seq_map() const { return !_seq_col_idx_to_value_cols_idx.empty(); }
754
755
0
    const std::unordered_map<uint32_t, uint32_t>& value_col_idx_to_seq_col_idx() const {
756
0
        return _value_col_idx_to_seq_col_idx;
757
0
    }
758
759
0
    void add_pruned_columns_data_type(int32_t col_unique_id, DataTypePtr data_type) {
760
0
        _pruned_columns_data_type[col_unique_id] = std::move(data_type);
761
0
    }
762
763
0
    void clear_pruned_columns_data_type() { _pruned_columns_data_type.clear(); }
764
765
0
    bool has_pruned_columns() const { return !_pruned_columns_data_type.empty(); }
766
767
13.2k
    TabletStorageFormatPB storage_format() const { return _storage_format; }
768
124
    void set_storage_format(TabletStorageFormatPB v) { _storage_format = v; }
769
770
private:
771
    friend bool operator==(const TabletSchema& a, const TabletSchema& b);
772
    friend bool operator!=(const TabletSchema& a, const TabletSchema& b);
773
7
    TabletSchema(const TabletSchema&) = default;
774
775
    KeysType _keys_type = DUP_KEYS;
776
    SortType _sort_type = SortType::LEXICAL;
777
    size_t _sort_col_num = 0;
778
    std::vector<TabletColumnPtr> _cols;
779
780
    std::vector<TabletIndexPtr> _indexes;
781
    std::unordered_map<StringRef, int32_t, StringRefHash> _field_name_to_index;
782
    std::unordered_map<int32_t, int32_t> _field_uniqueid_to_index;
783
    std::unordered_map<PathInDataRef, int32_t, PathInDataRef::Hash> _field_path_to_index;
784
785
    // index_type/col_unique_id/suffix -> idxs in _indexes
786
    using IndexKey = std::tuple<IndexType, int32_t, std::string>;
787
    struct IndexKeyHash {
788
42.0k
        size_t operator()(const IndexKey& t) const {
789
42.0k
            uint32_t seed = 0;
790
42.0k
            seed = doris::HashUtil::hash((const char*)&std::get<0>(t), sizeof(std::get<0>(t)),
791
42.0k
                                         seed);
792
42.0k
            seed = doris::HashUtil::hash((const char*)&std::get<1>(t), sizeof(std::get<1>(t)),
793
42.0k
                                         seed);
794
42.0k
            seed = doris::HashUtil::hash((const char*)std::get<2>(t).c_str(),
795
42.0k
                                         static_cast<uint32_t>(std::get<2>(t).size()), seed);
796
42.0k
            return seed;
797
42.0k
        }
798
    };
799
    std::unordered_map<IndexKey, std::vector<size_t>, IndexKeyHash> _col_id_suffix_to_index;
800
801
    int32_t _num_columns = 0;
802
    size_t _num_variant_columns = 0;
803
    size_t _num_virtual_columns = 0;
804
    size_t _num_key_columns = 0;
805
    std::vector<uint32_t> _cluster_key_uids;
806
    size_t _num_null_columns = 0;
807
    size_t _num_short_key_columns = 0;
808
    size_t _num_rows_per_row_block = 0;
809
    CompressKind _compress_kind = COMPRESS_NONE;
810
    segment_v2::CompressionTypePB _compression_type = segment_v2::CompressionTypePB::LZ4F;
811
    long _row_store_page_size = segment_v2::ROW_STORE_PAGE_SIZE_DEFAULT_VALUE;
812
    long _storage_page_size = segment_v2::STORAGE_PAGE_SIZE_DEFAULT_VALUE;
813
    long _storage_dict_page_size = segment_v2::STORAGE_DICT_PAGE_SIZE_DEFAULT_VALUE;
814
    size_t _next_column_unique_id = 0;
815
    std::string _auto_increment_column;
816
817
    bool _has_bf_fpp = false;
818
    double _bf_fpp = 0;
819
    bool _is_in_memory = false;
820
    int32_t _delete_sign_idx = -1;
821
    int32_t _sequence_col_idx = -1;
822
    int32_t _version_col_idx = -1;
823
    int32_t _skip_bitmap_col_idx = -1;
824
    int32_t _commit_tso_col_idx = -1;
825
    int32_t _binlog_tso_col_idx = -1;
826
    int32_t _binlog_lsn_col_idx = -1;
827
    int32_t _binlog_op_col_idx = -1;
828
    int32_t _schema_version = -1;
829
    int64_t _table_id = -1;
830
    int64_t _db_id = -1;
831
    bool _disable_auto_compaction = false;
832
    bool _store_row_column = false;
833
    bool _skip_write_index_on_load = false;
834
    InvertedIndexStorageFormatPB _inverted_index_storage_format = InvertedIndexStorageFormatPB::V1;
835
836
    // Contains column ids of which columns should be encoded into row store.
837
    // ATTN: For compability reason empty cids means all columns of tablet schema are encoded to row column
838
    std::vector<int32_t> _row_store_column_unique_ids;
839
    bool _deprecated_enable_variant_flatten_nested = false;
840
841
    std::map<size_t, int32_t> _vir_col_idx_to_unique_id;
842
    std::map<int32_t, DataTypePtr> _pruned_columns_data_type;
843
844
    // value: extracted path set and sparse path set
845
    std::unordered_map<int32_t, PathsSetInfo> _path_set_info_map;
846
847
    // key: field_pattern
848
    // value: indexes
849
    using PatternToIndex = std::unordered_map<std::string, std::vector<TabletIndexPtr>>;
850
    std::unordered_map<int32_t, PatternToIndex> _index_by_unique_id_with_pattern;
851
852
    // Default behavior for new segments: use external ColumnMeta region + CMO table if true
853
    // Persisted tablet storage format. Authoritative source for "is this tablet V3?"
854
    // decisions in the segment write paths. Old PBs without this field are upgraded in
855
    // init_from_pb() by deriving V3 from any of the three legacy V3-flavor flags.
856
    TabletStorageFormatPB _storage_format {TabletStorageFormatPB::TABLET_STORAGE_FORMAT_V2};
857
    // Sequence column unique id mapping to value columns unique id
858
    std::unordered_map<uint32_t, std::vector<uint32_t>> _seq_col_uid_to_value_cols_uid;
859
    // Value column unique id mapping to sequence column unique id(also map sequence column it self)
860
    std::unordered_map<uint32_t, uint32_t> _value_col_uid_to_seq_col_uid;
861
    // Sequence column index mapping to value column index
862
    std::unordered_map<uint32_t, std::vector<uint32_t>> _seq_col_idx_to_value_cols_idx;
863
    // Value column index mapping to sequence column index(also map sequence column it self)
864
    std::unordered_map<uint32_t, uint32_t> _value_col_idx_to_seq_col_idx;
865
};
866
867
bool operator==(const TabletSchema& a, const TabletSchema& b);
868
bool operator!=(const TabletSchema& a, const TabletSchema& b);
869
870
using TabletSchemaSPtr = std::shared_ptr<TabletSchema>;
871
872
} // namespace doris