Coverage Report

Created: 2026-09-16 05:29

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
    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
269M
    int32_t unique_id() const { return _unique_id; }
101
2.38k
    void set_unique_id(int32_t id) { _unique_id = id; }
102
431M
    const std::string& name() const { return _col_name; }
103
150k
    const std::string& name_lower_case() const { return _col_name_lower_case; }
104
304k
    void set_name(std::string col_name) {
105
304k
        _col_name = col_name;
106
304k
        _col_name_lower_case = to_lower(_col_name);
107
304k
    }
108
103M
    MOCK_FUNCTION FieldType type() const { return _type; }
109
247k
    void set_type(FieldType type) { _type = type; }
110
54.4M
    bool is_key() const { return _is_key; }
111
51.3M
    bool is_nullable() const { return _is_nullable; }
112
32
    bool is_auto_increment() const { return _is_auto_increment; }
113
36
    bool is_seqeunce_col() const { return _col_name == SEQUENCE_COL; }
114
7.60k
    bool is_on_update_current_timestamp() const { return _is_on_update_current_timestamp; }
115
118M
    bool is_variant_type() const { return _type == FieldType::OLAP_FIELD_TYPE_VARIANT; }
116
1.81M
    bool is_bf_column() const { return _is_bf_column; }
117
36.1M
    bool is_array_type() const { return _type == FieldType::OLAP_FIELD_TYPE_ARRAY; }
118
16.9M
    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
24.0k
    bool is_length_variable_type() const {
121
24.0k
        return _type == FieldType::OLAP_FIELD_TYPE_CHAR ||
122
24.0k
               _type == FieldType::OLAP_FIELD_TYPE_VARCHAR ||
123
24.0k
               _type == FieldType::OLAP_FIELD_TYPE_STRING ||
124
24.0k
               _type == FieldType::OLAP_FIELD_TYPE_HLL ||
125
24.0k
               _type == FieldType::OLAP_FIELD_TYPE_BITMAP ||
126
24.0k
               _type == FieldType::OLAP_FIELD_TYPE_QUANTILE_STATE ||
127
24.0k
               _type == FieldType::OLAP_FIELD_TYPE_AGG_STATE;
128
24.0k
    }
129
109k
    bool has_default_value() const { return _has_default_value; }
130
963k
    std::string default_value() const { return _default_value; }
131
20
    bool has_default_value_expr() const { return _has_default_value_expr; }
132
5
    const std::string& default_value_expr() const { return _default_value_expr; }
133
9.86M
    int32_t length() const { return _length; }
134
73.1k
    void set_length(int32_t length) { _length = length; }
135
32.6k
    void set_default_value(const std::string& default_value) {
136
32.6k
        _default_value = default_value;
137
32.6k
        _has_default_value = true;
138
32.6k
    }
139
    void set_default_value_expr(const std::string& default_value_expr) {
140
        _default_value_expr = default_value_expr;
141
        _has_default_value_expr = true;
142
    }
143
203k
    int32_t index_length() const { return _index_length; }
144
108k
    void set_index_length(int32_t index_length) { _index_length = index_length; }
145
    void set_is_key(bool is_key) { _is_key = is_key; }
146
86.5k
    void set_is_nullable(bool is_nullable) { _is_nullable = is_nullable; }
147
0
    void set_is_auto_increment(bool is_auto_increment) { _is_auto_increment = is_auto_increment; }
148
0
    void set_is_on_update_current_timestamp(bool is_on_update_current_timestamp) {
149
0
        _is_on_update_current_timestamp = is_on_update_current_timestamp;
150
0
    }
151
    void set_path_info(const PathInData& path);
152
794k
    FieldAggregationMethod aggregation() const { return _aggregation; }
153
    AggregateFunctionPtr get_aggregate_function_union(DataTypePtr type,
154
                                                      int current_be_exec_version) const;
155
    AggregateFunctionPtr get_aggregate_function(std::string suffix,
156
                                                int current_be_exec_version) const;
157
    AggregateFunctionPtr get_aggregate_function(std::string suffix, int current_be_exec_version,
158
                                                DataTypePtr runtime_type) const;
159
7.16M
    int precision() const { return _precision; }
160
23.2M
    int frac() const { return _frac; }
161
9.04k
    inline bool visible() const { return _visible; }
162
    bool has_char_type() const;
163
164
114k
    void set_aggregation_method(FieldAggregationMethod agg) {
165
114k
        _aggregation = agg;
166
114k
        _aggregation_name = get_string_by_aggregation_type(agg);
167
114k
    }
168
169
    /**
170
     * Add a sub column.
171
     */
172
    void add_sub_column(TabletColumn& sub_column);
173
174
1.80M
    uint32_t get_subtype_count() const { return _sub_column_count; }
175
788k
    MOCK_FUNCTION const TabletColumn& get_sub_column(uint64_t i) const { return *_sub_columns[i]; }
176
254k
    const std::vector<TabletColumnPtr>& get_sub_columns() const { return _sub_columns; }
177
178
    friend bool operator==(const TabletColumn& a, const TabletColumn& b);
179
    friend bool operator!=(const TabletColumn& a, const TabletColumn& b);
180
181
    static std::string get_string_by_field_type(FieldType type);
182
    static std::string get_string_by_aggregation_type(FieldAggregationMethod aggregation_type);
183
    static FieldType get_field_type_by_string(const std::string& str);
184
    static FieldAggregationMethod get_aggregation_type_by_string(const std::string& str);
185
    static uint32_t get_field_length_by_type(TPrimitiveType::type type, uint32_t string_length);
186
    bool is_row_store_column() const;
187
813k
    std::string get_aggregation_name() const { return _aggregation_name; }
188
813k
    bool get_result_is_nullable() const { return _result_is_nullable; }
189
869k
    int get_be_exec_version() const { return _be_exec_version; }
190
57.3M
    bool has_path_info() const { return _column_path != nullptr && !_column_path->empty(); }
191
20.1M
    const PathInDataPtr& path_info_ptr() const { return _column_path; }
192
    // If it is an extracted column from variant column
193
181M
    bool is_extracted_column() const {
194
181M
        return _column_path != nullptr && !_column_path->empty() && _parent_col_unique_id >= 0;
195
181M
    };
196
18.3M
    std::string suffix_path() const {
197
18.3M
        return is_extracted_column() ? _column_path->get_path() : "";
198
18.3M
    }
199
43.9k
    bool is_nested_subcolumn() const {
200
43.9k
        return _column_path != nullptr && _column_path->has_nested_part();
201
43.9k
    }
202
647k
    int32_t parent_unique_id() const { return _parent_col_unique_id; }
203
121k
    void set_parent_unique_id(int32_t col_unique_id) { _parent_col_unique_id = col_unique_id; }
204
67.7k
    void set_is_bf_column(bool is_bf_column) { _is_bf_column = is_bf_column; }
205
    std::shared_ptr<const IDataType> get_vec_type() const;
206
207
113k
    Status check_valid() const {
208
113k
        if (type() != FieldType::OLAP_FIELD_TYPE_ARRAY &&
209
113k
            type() != FieldType::OLAP_FIELD_TYPE_STRUCT &&
210
113k
            type() != FieldType::OLAP_FIELD_TYPE_MAP) {
211
109k
            return Status::OK();
212
109k
        }
213
3.87k
        if (is_bf_column()) {
214
0
            return Status::NotSupported("Do not support bloom filter index, type={}",
215
0
                                        get_string_by_field_type(type()));
216
0
        }
217
3.87k
        return Status::OK();
218
3.87k
    }
219
220
4.75k
    void set_precision(int precision) {
221
4.75k
        _precision = precision;
222
4.75k
        _is_decimal = true;
223
4.75k
    }
224
225
5.08k
    void set_frac(int frac) { _frac = frac; }
226
227
0
    const VariantParams& variant_params() const { return _variant; }
228
0
    VariantParams* mutable_variant_params() { return &_variant; }
229
230
61.5k
    int32_t variant_max_subcolumns_count() const { return _variant.max_subcolumns_count; }
231
232
7.61k
    void set_variant_max_subcolumns_count(int32_t variant_max_subcolumns_count) {
233
7.61k
        _variant.max_subcolumns_count = variant_max_subcolumns_count;
234
7.61k
    }
235
236
26.9k
    PatternTypePB pattern_type() const { return _pattern_type; }
237
238
12.1k
    bool variant_enable_typed_paths_to_sparse() const {
239
12.1k
        return _variant.enable_typed_paths_to_sparse;
240
12.1k
    }
241
242
46.9k
    int32_t variant_max_sparse_column_statistics_size() const {
243
46.9k
        return _variant.max_sparse_column_statistics_size;
244
46.9k
    }
245
246
8.70k
    int32_t variant_sparse_hash_shard_count() const { return _variant.sparse_hash_shard_count; }
247
248
85.8k
    bool variant_enable_doc_mode() const { return _variant.enable_doc_mode; }
249
250
5.25k
    int64_t variant_doc_materialization_min_rows() const {
251
5.25k
        return _variant.doc_materialization_min_rows;
252
5.25k
    }
253
254
7.39k
    int32_t variant_doc_hash_shard_count() const { return _variant.doc_hash_shard_count; }
255
256
    void set_variant_doc_materialization_min_rows(int64_t variant_doc_materialization_min_rows) {
257
        _variant.doc_materialization_min_rows = variant_doc_materialization_min_rows;
258
    }
259
260
    void set_variant_doc_hash_shard_count(int32_t variant_doc_hash_shard_count) {
261
        _variant.doc_hash_shard_count = variant_doc_hash_shard_count;
262
    }
263
264
    void set_variant_max_sparse_column_statistics_size(
265
            int32_t variant_max_sparse_column_statistics_size) {
266
        _variant.max_sparse_column_statistics_size = variant_max_sparse_column_statistics_size;
267
    }
268
269
    void set_variant_sparse_hash_shard_count(int32_t variant_sparse_hash_shard_count) {
270
        _variant.sparse_hash_shard_count = variant_sparse_hash_shard_count;
271
    }
272
273
8.27k
    void set_variant_enable_doc_mode(bool variant_enable_doc_mode) {
274
8.27k
        _variant.enable_doc_mode = variant_enable_doc_mode;
275
8.27k
    }
276
277
    void set_variant_enable_typed_paths_to_sparse(bool variant_enable_typed_paths_to_sparse) {
278
        _variant.enable_typed_paths_to_sparse = variant_enable_typed_paths_to_sparse;
279
    }
280
281
170k
    bool variant_enable_nested_group() const { return _variant.enable_nested_group; }
282
283
    void set_variant_enable_nested_group(bool val) { _variant.enable_nested_group = val; }
284
285
5.07k
    bool is_decimal() const { return _is_decimal; }
286
287
private:
288
    int32_t _unique_id = -1;
289
    std::string _col_name;
290
    std::string _col_name_lower_case;
291
    // the field _type will change from TPrimitiveType
292
    // to string by 'EnumToString(TPrimitiveType, tcolumn.column_type.type, data_type);' (reference: TabletMeta::init_column_from_tcolumn)
293
    // to FieldType by 'TabletColumn::get_field_type_by_string' (reference: TabletColumn::init_from_pb).
294
    // And the _type in columnPB is string and it changed from FieldType by 'get_string_by_field_type' (reference: TabletColumn::to_schema_pb).
295
    FieldType _type;
296
    bool _is_key = false;
297
    FieldAggregationMethod _aggregation;
298
    std::string _aggregation_name;
299
    bool _is_nullable = false;
300
    bool _is_auto_increment = false;
301
    bool _is_on_update_current_timestamp {false};
302
303
    bool _has_default_value = false;
304
    std::string _default_value;
305
    bool _has_default_value_expr = false;
306
    std::string _default_value_expr;
307
308
    bool _is_decimal = false;
309
    int32_t _precision = -1;
310
    int32_t _frac = -1;
311
312
    int32_t _length = -1;
313
    int32_t _index_length = -1;
314
315
    bool _is_bf_column = false;
316
317
    bool _visible = true;
318
319
    std::vector<TabletColumnPtr> _sub_columns;
320
    uint32_t _sub_column_count = 0;
321
322
    bool _result_is_nullable = false;
323
    int _be_exec_version = -1;
324
325
    // The extracted sub-columns from "variant" contain the following information:
326
    int32_t _parent_col_unique_id = -1; // "variant" -> col_unique_id
327
    PathInDataPtr _column_path;         // the path of the sub-columns themselves
328
    PatternTypePB _pattern_type = PatternTypePB::MATCH_NAME_GLOB;
329
330
    VariantParams _variant;
331
};
332
333
bool operator==(const TabletColumn& a, const TabletColumn& b);
334
bool operator!=(const TabletColumn& a, const TabletColumn& b);
335
336
class TabletIndex : public MetadataAdder<TabletIndex> {
337
public:
338
1.15M
    TabletIndex() = default;
339
    void init_from_thrift(const TOlapTableIndex& index, const TabletSchema& tablet_schema);
340
    void init_from_thrift(const TOlapTableIndex& index, const std::vector<int32_t>& column_uids);
341
    void init_from_pb(const TabletIndexPB& index);
342
    void to_schema_pb(TabletIndexPB* index) const;
343
344
464k
    int64_t index_id() const { return _index_id; }
345
    const std::string& index_name() const { return _index_name; }
346
1.55M
    MOCK_FUNCTION IndexType index_type() const { return _index_type; }
347
1.33M
    const std::vector<int32_t>& col_unique_ids() const { return _col_unique_ids; }
348
893k
    MOCK_FUNCTION const std::map<std::string, std::string>& properties() const {
349
893k
        return _properties;
350
893k
    }
351
3.38k
    int32_t get_gram_size() const {
352
3.38k
        if (_properties.contains("gram_size")) {
353
3.38k
            return std::stoi(_properties.at("gram_size"));
354
3.38k
        }
355
356
18.4E
        return 0;
357
3.38k
    }
358
3.38k
    int32_t get_gram_bf_size() const {
359
3.38k
        if (_properties.contains("bf_size")) {
360
3.38k
            return std::stoi(_properties.at("bf_size"));
361
3.38k
        }
362
363
18.4E
        return 0;
364
3.38k
    }
365
366
1.44M
    const std::string& get_index_suffix() const { return _escaped_index_suffix_path; }
367
368
    void set_escaped_escaped_index_suffix_path(const std::string& name);
369
370
35.7k
    bool is_inverted_index() const { return _index_type == IndexType::INVERTED; }
371
372
46
    bool is_ann_index() const { return _index_type == IndexType::ANN; }
373
374
1.31k
    void remove_parser_and_analyzer() {
375
1.31k
        _properties.erase(INVERTED_INDEX_PARSER_KEY);
376
1.31k
        _properties.erase(INVERTED_INDEX_PARSER_KEY_ALIAS);
377
1.31k
        _properties.erase(INVERTED_INDEX_ANALYZER_NAME_KEY);
378
1.31k
        _properties.erase(INVERTED_INDEX_NORMALIZER_NAME_KEY);
379
1.31k
    }
380
381
1.24M
    std::string field_pattern() const {
382
1.24M
        if (_properties.contains("field_pattern")) {
383
8.36k
            return _properties.at("field_pattern");
384
8.36k
        }
385
1.23M
        return "";
386
1.24M
    }
387
388
339
    bool is_same_except_id(const TabletIndex* other) const {
389
339
        return _escaped_index_suffix_path == other->_escaped_index_suffix_path &&
390
339
               _index_name == other->_index_name && _index_type == other->_index_type &&
391
339
               _col_unique_ids == other->_col_unique_ids && _properties == other->_properties;
392
339
    }
393
394
private:
395
    int64_t _index_id = -1;
396
    // Identify the different index with the same _index_id
397
    std::string _escaped_index_suffix_path;
398
    std::string _index_name;
399
    IndexType _index_type;
400
    std::vector<int32_t> _col_unique_ids;
401
    std::map<std::string, std::string> _properties;
402
};
403
404
using TabletIndexPtr = std::shared_ptr<TabletIndex>;
405
using TabletIndexes = std::vector<std::shared_ptr<TabletIndex>>;
406
using PathSet = phmap::flat_hash_set<std::string>;
407
408
class TabletSchema : public MetadataAdder<TabletSchema> {
409
public:
410
    enum class ColumnType { NORMAL = 0, VARIANT = 1 };
411
    // TODO(yingchun): better to make constructor as private to avoid
412
    // manually init members incorrectly, and define a new function like
413
    // void create_from_pb(const TabletSchemaPB& schema, TabletSchema* tablet_schema).
414
    TabletSchema();
415
    ~TabletSchema() override;
416
417
    // Init from pb
418
    // ignore_extracted_columns: ignore the extracted columns from variant column
419
    // reuse_cached_column: reuse the cached column in the schema if they are the same, to reduce memory usage
420
    void init_from_pb(const TabletSchemaPB& schema, bool ignore_extracted_columns = false,
421
                      bool reuse_cached_column = false);
422
    // Notice: Use deterministic way to serialize protobuf,
423
    // since serialize Map in protobuf may could lead to un-deterministic by default
424
    template <class PbType>
425
3.53M
    static std::string deterministic_string_serialize(const PbType& pb) {
426
3.53M
        std::string output;
427
3.53M
        google::protobuf::io::StringOutputStream string_output_stream(&output);
428
3.53M
        google::protobuf::io::CodedOutputStream output_stream(&string_output_stream);
429
3.53M
        output_stream.SetSerializationDeterministic(true);
430
3.53M
        pb.SerializeToCodedStream(&output_stream);
431
3.53M
        return output;
432
3.53M
    }
_ZN5doris12TabletSchema30deterministic_string_serializeINS_8ColumnPBEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Line
Count
Source
425
1.21M
    static std::string deterministic_string_serialize(const PbType& pb) {
426
1.21M
        std::string output;
427
1.21M
        google::protobuf::io::StringOutputStream string_output_stream(&output);
428
1.21M
        google::protobuf::io::CodedOutputStream output_stream(&string_output_stream);
429
1.21M
        output_stream.SetSerializationDeterministic(true);
430
1.21M
        pb.SerializeToCodedStream(&output_stream);
431
1.21M
        return output;
432
1.21M
    }
_ZN5doris12TabletSchema30deterministic_string_serializeINS_13TabletIndexPBEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Line
Count
Source
425
116k
    static std::string deterministic_string_serialize(const PbType& pb) {
426
116k
        std::string output;
427
116k
        google::protobuf::io::StringOutputStream string_output_stream(&output);
428
116k
        google::protobuf::io::CodedOutputStream output_stream(&string_output_stream);
429
116k
        output_stream.SetSerializationDeterministic(true);
430
116k
        pb.SerializeToCodedStream(&output_stream);
431
116k
        return output;
432
116k
    }
_ZN5doris12TabletSchema30deterministic_string_serializeINS_14TabletSchemaPBEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Line
Count
Source
425
2.02M
    static std::string deterministic_string_serialize(const PbType& pb) {
426
2.02M
        std::string output;
427
2.02M
        google::protobuf::io::StringOutputStream string_output_stream(&output);
428
2.02M
        google::protobuf::io::CodedOutputStream output_stream(&string_output_stream);
429
2.02M
        output_stream.SetSerializationDeterministic(true);
430
2.02M
        pb.SerializeToCodedStream(&output_stream);
431
2.02M
        return output;
432
2.02M
    }
_ZN5doris12TabletSchema30deterministic_string_serializeINS_21POlapTableIndexSchemaEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Line
Count
Source
425
177k
    static std::string deterministic_string_serialize(const PbType& pb) {
426
177k
        std::string output;
427
177k
        google::protobuf::io::StringOutputStream string_output_stream(&output);
428
177k
        google::protobuf::io::CodedOutputStream output_stream(&string_output_stream);
429
177k
        output_stream.SetSerializationDeterministic(true);
430
177k
        pb.SerializeToCodedStream(&output_stream);
431
177k
        return output;
432
177k
    }
433
    void to_schema_pb(TabletSchemaPB* tablet_meta_pb) const;
434
    void append_column(TabletColumn column, ColumnType col_type = ColumnType::NORMAL);
435
    void append_index(TabletIndex&& index);
436
    void remove_index(int64_t index_id);
437
    void clear_index();
438
    // Must make sure the row column is always the last column
439
    void add_row_column();
440
    void copy_from(const TabletSchema& tablet_schema);
441
    // lightweight copy, take care of lifecycle of TabletColumn
442
    void shawdow_copy_without_columns(const TabletSchema& tablet_schema);
443
    void update_index_info_from(const TabletSchema& tablet_schema);
444
    std::string to_key() const;
445
    // get_metadata_size is only the memory of the TabletSchema itself, not include child objects.
446
110k
    int64_t mem_size() const { return get_metadata_size(); }
447
    size_t row_size() const;
448
    int32_t field_index(const std::string& field_name) const;
449
    int32_t field_index(const PathInData& path) const;
450
    int32_t field_index(int32_t col_unique_id) const;
451
    const TabletColumn& column(size_t ordinal) const;
452
    Result<const TabletColumn*> column(const std::string& field_name) const;
453
    Status have_column(const std::string& field_name) const;
454
    bool exist_column(const std::string& field_name) const;
455
    bool has_column_unique_id(int32_t col_unique_id) const;
456
    const TabletColumn& column_by_uid(int32_t col_unique_id) const;
457
    TabletColumn& mutable_column_by_uid(int32_t col_unique_id);
458
    TabletColumn& mutable_column(size_t ordinal);
459
    void replace_column(size_t pos, TabletColumn new_col);
460
    const std::vector<TabletColumnPtr>& columns() const;
461
8.64M
    size_t num_columns() const { return _num_columns; }
462
0
    size_t num_visible_columns() const {
463
0
        return std::count_if(_cols.begin(), _cols.end(),
464
0
                             [](const TabletColumnPtr& column) { return column->visible(); });
465
0
    }
466
    size_t num_visible_value_columns() const {
467
        return std::count_if(_cols.begin(), _cols.end(), [](const TabletColumnPtr& column) {
468
            return column->visible() && !column->is_key();
469
        });
470
    }
471
    // num_key_columns: Total number of sort key columns in the table, determined by the key columns
472
    // specified in DUPLICATE KEY/UNIQUE KEY/AGGREGATE KEY when creating the table, used for complete data sorting
473
    // Example: CREATE TABLE t(a INT, b DATE, c VARCHAR) DUPLICATE KEY(a, b, c)
474
    //          Then num_key_columns = 3 (columns a, b, c are all sort keys)
475
5.27M
    size_t num_key_columns() const { return _num_key_columns; }
476
14.4M
    const std::vector<uint32_t>& cluster_key_uids() const { return _cluster_key_uids; }
477
0
    size_t num_null_columns() const { return _num_null_columns; }
478
    // num_short_key_columns: Number of columns used to build the Short Key Index, automatically calculated by FE
479
    // Limited by max column count (default 3) and max bytes (default 36 bytes). Types like float/double/STRING/JSONB
480
    // cannot be used as short keys. VARCHAR can only be the last short key column. Optimizes index size and query performance.
481
    // Example: CREATE TABLE t(a INT, b DATE, c VARCHAR) DUPLICATE KEY(a, b, c)
482
    //          Then num_short_key_columns = 3 (a, b, c all meet criteria, c as VARCHAR is the last short key)
483
    // Example: CREATE TABLE t(a INT, b DOUBLE, c DATE) DUPLICATE KEY(a, b, c)
484
    //          Then num_short_key_columns = 1 (b is DOUBLE type which cannot be short key, stops at b)
485
    // short key's size is limited to 36 bytes, because it will be loaded to memory during segment loaded.
486
1.08M
    size_t num_short_key_columns() const { return _num_short_key_columns; }
487
69.3k
    size_t num_rows_per_row_block() const { return _num_rows_per_row_block; }
488
1.46M
    size_t num_variant_columns() const { return _num_variant_columns; };
489
0
    size_t num_virtual_columns() const { return _num_virtual_columns; }
490
42.5M
    KeysType keys_type() const { return _keys_type; }
491
1.39M
    SortType sort_type() const { return _sort_type; }
492
68.9k
    size_t sort_col_num() const { return _sort_col_num; }
493
367k
    CompressKind compress_kind() const { return _compress_kind; }
494
69.0k
    size_t next_column_unique_id() const { return _next_column_unique_id; }
495
2.20k
    bool has_bf_fpp() const { return _has_bf_fpp; }
496
9.48k
    double bloom_filter_fpp() const { return _bf_fpp; }
497
19.4M
    bool is_in_memory() const { return _is_in_memory; }
498
1
    void set_is_in_memory(bool is_in_memory) { _is_in_memory = is_in_memory; }
499
18
    void set_disable_auto_compaction(bool disable_auto_compaction) {
500
18
        _disable_auto_compaction = disable_auto_compaction;
501
18
    }
502
1.29G
    bool disable_auto_compaction() const { return _disable_auto_compaction; }
503
    // Deprecated legacy switch for flatten-nested variant behavior.
504
    // It is distinct from variant_enable_nested_group.
505
0
    void set_deprecated_variant_flatten_nested(bool flatten_nested) {
506
0
        _deprecated_enable_variant_flatten_nested = flatten_nested;
507
0
    }
508
79.8k
    bool deprecated_variant_flatten_nested() const {
509
79.8k
        return _deprecated_enable_variant_flatten_nested;
510
79.8k
    }
511
    // indicate if full row store column(all the columns encodes as row) exists
512
6.21k
    bool has_row_store_for_all_columns() const {
513
6.21k
        return _store_row_column && row_columns_uids().empty();
514
6.21k
    }
515
0
    void set_skip_write_index_on_load(bool skip) { _skip_write_index_on_load = skip; }
516
687k
    bool skip_write_index_on_load() const { return _skip_write_index_on_load; }
517
14.1k
    int32_t delete_sign_idx() const { return _delete_sign_idx; }
518
22.0M
    bool has_sequence_col() const { return _sequence_col_idx != -1; }
519
159k
    int32_t sequence_col_idx() const { return _sequence_col_idx; }
520
0
    void set_version_col_idx(int32_t version_col_idx) { _version_col_idx = version_col_idx; }
521
9.07k
    int32_t version_col_idx() const { return _version_col_idx; }
522
573
    bool has_skip_bitmap_col() const { return _skip_bitmap_col_idx != -1; }
523
11.5k
    int32_t skip_bitmap_col_idx() const { return _skip_bitmap_col_idx; }
524
303k
    bool is_tso_enabled() const { return _commit_tso_col_idx != -1 || _binlog_tso_col_idx != -1; }
525
14.1k
    int32_t commit_tso_col_idx() const { return _commit_tso_col_idx; }
526
258k
    int32_t row_lsn_col_idx() const { return _row_lsn_col_idx; }
527
5.38k
    int32_t binlog_tso_col_idx() const { return _binlog_tso_col_idx; }
528
4.74k
    int32_t binlog_lsn_col_idx() const { return _binlog_lsn_col_idx; }
529
4.07k
    int32_t binlog_op_col_idx() const { return _binlog_op_col_idx; }
530
14.5k
    segment_v2::CompressionTypePB compression_type() const { return _compression_type; }
531
0
    void set_row_store_page_size(long page_size) { _row_store_page_size = page_size; }
532
70.5k
    long row_store_page_size() const { return _row_store_page_size; }
533
    void set_storage_page_size(long storage_page_size) { _storage_page_size = storage_page_size; }
534
789k
    long storage_page_size() const { return _storage_page_size; }
535
0
    void set_storage_dict_page_size(long storage_dict_page_size) {
536
0
        _storage_dict_page_size = storage_dict_page_size;
537
0
    }
538
788k
    long storage_dict_page_size() const { return _storage_dict_page_size; }
539
884k
    bool has_global_row_id() const {
540
14.0M
        for (auto [col_name, _] : _field_name_to_index) {
541
14.0M
            if (col_name.start_with(StringRef(BeConsts::GLOBAL_ROWID_COL.data(),
542
14.0M
                                              BeConsts::GLOBAL_ROWID_COL.size()))) {
543
8.30k
                return true;
544
8.30k
            }
545
14.0M
        }
546
876k
        return false;
547
884k
    }
548
549
13.8k
    const std::vector<const TabletIndex*> inverted_indexes() const {
550
13.8k
        std::vector<const TabletIndex*> inverted_indexes;
551
13.8k
        for (const auto& index : _indexes) {
552
6.04k
            if (index->index_type() == IndexType::INVERTED) {
553
5.19k
                inverted_indexes.emplace_back(index.get());
554
5.19k
            }
555
6.04k
        }
556
13.8k
        return inverted_indexes;
557
13.8k
    }
558
    // True when anything at all lives in this schema's inverted index FILE.
559
    //
560
    // Spelled out as `has_inverted_index() || has_ann_index()` at ~27 call sites
561
    // before this existed -- rowset writers, segment creation, segcompaction,
562
    // snapshot and migration, and most of the cloud paths. Every one of them is
563
    // asking the same question ("is there an index file to carry, warm, link or
564
    // rewrite?"), and each open-coded copy is a place a third index type would
565
    // have to be remembered.
566
401k
    bool has_inverted_or_ann_index() const { return has_inverted_index() || has_ann_index(); }
567
568
    // Both index types that live in the inverted index FILE, in schema order.
569
    // Every storage format stores them together: V1/V2/V3 as CLucene directories,
570
    // SNII as text metadata groups plus an ANN blob logical index. A rewrite that
571
    // enumerated only the inverted ones would seal a file missing every ANN index
572
    // while the schema still claimed them.
573
25
    const std::vector<const TabletIndex*> inverted_and_ann_indexes() const {
574
25
        std::vector<const TabletIndex*> indexes;
575
31
        for (const auto& index : _indexes) {
576
31
            if (index->index_type() == IndexType::INVERTED ||
577
31
                index->index_type() == IndexType::ANN) {
578
31
                indexes.emplace_back(index.get());
579
31
            }
580
31
        }
581
25
        return indexes;
582
25
    }
583
467k
    bool has_inverted_index() const {
584
467k
        for (const auto& index : _indexes) {
585
44.9k
            DBUG_EXECUTE_IF("tablet_schema::has_inverted_index", {
586
44.9k
                if (index->col_unique_ids().empty()) {
587
44.9k
                    throw Exception(Status::InternalError("col unique ids cannot be empty"));
588
44.9k
                }
589
44.9k
            });
590
591
44.9k
            if (index->index_type() == IndexType::INVERTED) {
592
                //if index_id == -1, ignore it.
593
44.1k
                if (!index->col_unique_ids().empty() && index->col_unique_ids()[0] >= 0) {
594
44.1k
                    return true;
595
44.1k
                }
596
44.1k
            }
597
44.9k
        }
598
423k
        return false;
599
467k
    }
600
601
361k
    bool has_ann_index() const {
602
361k
        for (const auto& index : _indexes) {
603
722
            if (index->index_type() == IndexType::ANN) {
604
360
                if (!index->col_unique_ids().empty() && index->col_unique_ids()[0] >= 0) {
605
360
                    return true;
606
360
                }
607
360
            }
608
722
        }
609
360k
        return false;
610
361k
    }
611
612
    bool has_inverted_index_with_index_id(int64_t index_id) const;
613
614
    std::vector<const TabletIndex*> inverted_indexs(const TabletColumn& col) const;
615
616
    std::vector<const TabletIndex*> inverted_indexs(int32_t col_unique_id,
617
                                                    const std::string& suffix_path = "") const;
618
    const TabletIndex* ann_index(const TabletColumn& col) const;
619
620
    // Regardless of whether this column supports inverted index
621
    // TabletIndex information will be returned as long as it exists.
622
    const TabletIndex* ann_index(int32_t col_unique_id, const std::string& suffix_path = "") const;
623
624
    std::vector<TabletIndexPtr> inverted_index_by_field_pattern(
625
            int32_t col_unique_id, const std::string& field_pattern) const;
626
627
    bool has_ngram_bf_index(int32_t col_unique_id) const;
628
    const TabletIndex* get_ngram_bf_index(int32_t col_unique_id) const;
629
    double get_bloom_filter_fpp(int32_t col_unique_id) const;
630
    double get_bloom_filter_fpp(const TabletColumn& column) const;
631
    const TabletIndex* get_index(int32_t col_unique_id, IndexType index_type,
632
                                 const std::string& suffix_path) const;
633
    void update_indexes_from_thrift(const std::vector<doris::TOlapTableIndex>& indexes);
634
    // If schema version is not set, it should be -1
635
1.38M
    int32_t schema_version() const { return _schema_version; }
636
    void clear_columns();
637
    // Each column id is an ordinal in TabletSchema::_cols, not a unique id or ReadSchema ordinal.
638
    // The resulting Block uses the selected physical TabletSchema column types.
639
    Block create_storage_block(const std::vector<uint32_t>& column_ids) const;
640
    Block create_storage_block() const;
641
1.06M
    void set_schema_version(int32_t version) { _schema_version = version; }
642
1.01k
    void set_auto_increment_column(const std::string& auto_increment_column) {
643
1.01k
        _auto_increment_column = auto_increment_column;
644
1.01k
    }
645
2.62k
    std::string auto_increment_column() const { return _auto_increment_column; }
646
647
70.2k
    void set_table_id(int64_t table_id) { _table_id = table_id; }
648
933k
    int64_t table_id() const { return _table_id; }
649
70.3k
    void set_db_id(int64_t db_id) { _db_id = db_id; }
650
462
    int64_t db_id() const { return _db_id; }
651
    void build_current_tablet_schema(int64_t index_id, int32_t version,
652
                                     const OlapTableIndexSchema* index,
653
                                     const TabletSchema& out_tablet_schema);
654
655
    // copy extracted columns from src_schema
656
    void copy_extracted_columns(const TabletSchema& src_schema);
657
658
    // only reserve extracted columns
659
    void reserve_extracted_columns();
660
661
4.04k
    std::string get_all_field_names() const {
662
4.04k
        std::string str = "[";
663
4.04k
        for (auto p : _field_name_to_index) {
664
4.04k
            if (str.size() > 1) {
665
0
                str += ", ";
666
0
            }
667
4.04k
            str += p.first.to_string() + "(" + std::to_string(_cols[p.second]->unique_id()) + ")";
668
4.04k
        }
669
4.04k
        str += "]";
670
4.04k
        return str;
671
4.04k
    }
672
673
    // Dump [(name, type, is_nullable), ...]
674
5
    std::string dump_structure() const {
675
5
        std::string str = "[";
676
28
        for (auto p : _cols) {
677
28
            if (str.size() > 1) {
678
23
                str += ", ";
679
23
            }
680
28
            str += "(";
681
28
            str += p->name();
682
28
            str += ", ";
683
28
            str += TabletColumn::get_string_by_field_type(p->type());
684
28
            str += ", ";
685
28
            str += "is_nullable:";
686
28
            str += (p->is_nullable() ? "true" : "false");
687
28
            str += ")";
688
28
        }
689
5
        str += "]";
690
5
        return str;
691
5
    }
692
693
1
    std::string dump_full_schema() const {
694
1
        std::string str = "[";
695
4
        for (auto p : _cols) {
696
4
            if (str.size() > 1) {
697
3
                str += ", ";
698
3
            }
699
4
            ColumnPB col_pb;
700
4
            p->to_schema_pb(&col_pb);
701
4
            str += "(";
702
4
            str += col_pb.ShortDebugString();
703
4
            str += ")";
704
4
        }
705
1
        str += "]";
706
1
        return str;
707
1
    }
708
709
    std::shared_ptr<TabletSchema> copy_without_variant_extracted_columns();
710
1.75M
    InvertedIndexStorageFormatPB get_inverted_index_storage_format() const {
711
1.75M
        return _inverted_index_storage_format;
712
1.75M
    }
713
714
    void update_tablet_columns(const TabletSchema& tablet_schema,
715
                               const std::vector<TColumn>& t_columns);
716
717
12.0k
    const std::vector<int32_t>& row_columns_uids() const { return _row_store_column_unique_ids; }
718
719
    int64_t get_metadata_size() const override;
720
721
    struct SubColumnInfo {
722
        TabletColumn column;
723
        TabletIndexes indexes;
724
    };
725
726
    // all path in path_set_info are relative to the parent column
727
    struct PathsSetInfo {
728
        std::unordered_map<std::string, SubColumnInfo> typed_path_set;    // typed columns
729
        std::unordered_map<std::string, TabletIndexes> subcolumn_indexes; // subcolumns indexes
730
        PathSet sub_path_set;                                             // extracted columns
731
        PathSet sparse_path_set;                                          // sparse columns
732
733
        // "Materialized regular path" means compaction chose to store this path as a dedicated
734
        // column in the schema, either typed or extracted, instead of re-emitting it dynamically.
735
0
        bool contains_materialized_regular_path(const std::string& path) const {
736
0
            return typed_path_set.contains(path) || sub_path_set.contains(path);
737
0
        }
738
    };
739
740
10.2k
    void set_path_set_info(std::unordered_map<int32_t, PathsSetInfo>&& path_set_info_map) {
741
10.2k
        _path_set_info_map = std::move(path_set_info_map);
742
10.2k
    }
743
744
5.28k
    const PathsSetInfo& path_set_info(int32_t unique_id) const {
745
5.28k
        return _path_set_info_map.at(unique_id);
746
5.28k
    }
747
748
    const PathsSetInfo* try_path_set_info(int32_t unique_id) const {
749
        auto it = _path_set_info_map.find(unique_id);
750
        return it == _path_set_info_map.end() ? nullptr : &it->second;
751
    }
752
753
    bool need_record_variant_extended_schema() const { return variant_max_subcolumns_count() == 0; }
754
755
    int32_t variant_max_subcolumns_count() const {
756
        for (const auto& col : _cols) {
757
            if (col->is_variant_type()) {
758
                return col->variant_max_subcolumns_count();
759
            }
760
        }
761
        return 0;
762
    }
763
    const std::unordered_map<uint32_t, std::vector<uint32_t>>& seq_col_idx_to_value_cols_idx()
764
22
            const {
765
22
        return _seq_col_idx_to_value_cols_idx;
766
22
    }
767
768
3.32M
    bool has_seq_map() const { return !_seq_col_idx_to_value_cols_idx.empty(); }
769
770
791k
    TabletStorageFormatPB storage_format() const { return _storage_format; }
771
176
    void set_storage_format(TabletStorageFormatPB v) { _storage_format = v; }
772
773
private:
774
    friend bool operator==(const TabletSchema& a, const TabletSchema& b);
775
    friend bool operator!=(const TabletSchema& a, const TabletSchema& b);
776
    TabletSchema(const TabletSchema&) = default;
777
778
    KeysType _keys_type = DUP_KEYS;
779
    SortType _sort_type = SortType::LEXICAL;
780
    size_t _sort_col_num = 0;
781
    std::vector<TabletColumnPtr> _cols;
782
783
    std::vector<TabletIndexPtr> _indexes;
784
    std::unordered_map<StringRef, int32_t, StringRefHash> _field_name_to_index;
785
    std::unordered_map<int32_t, int32_t> _field_uniqueid_to_index;
786
    std::unordered_map<PathInDataRef, int32_t, PathInDataRef::Hash> _field_path_to_index;
787
788
    // index_type/col_unique_id/suffix -> idxs in _indexes
789
    using IndexKey = std::tuple<IndexType, int32_t, std::string>;
790
    struct IndexKeyHash {
791
20.4M
        size_t operator()(const IndexKey& t) const {
792
20.4M
            uint32_t seed = 0;
793
20.4M
            seed = doris::HashUtil::hash((const char*)&std::get<0>(t), sizeof(std::get<0>(t)),
794
20.4M
                                         seed);
795
20.4M
            seed = doris::HashUtil::hash((const char*)&std::get<1>(t), sizeof(std::get<1>(t)),
796
20.4M
                                         seed);
797
20.4M
            seed = doris::HashUtil::hash((const char*)std::get<2>(t).c_str(),
798
20.4M
                                         static_cast<uint32_t>(std::get<2>(t).size()), seed);
799
20.4M
            return seed;
800
20.4M
        }
801
    };
802
    std::unordered_map<IndexKey, std::vector<size_t>, IndexKeyHash> _col_id_suffix_to_index;
803
804
    int32_t _num_columns = 0;
805
    size_t _num_variant_columns = 0;
806
    size_t _num_virtual_columns = 0;
807
    size_t _num_key_columns = 0;
808
    std::vector<uint32_t> _cluster_key_uids;
809
    size_t _num_null_columns = 0;
810
    size_t _num_short_key_columns = 0;
811
    size_t _num_rows_per_row_block = 0;
812
    CompressKind _compress_kind = COMPRESS_NONE;
813
    segment_v2::CompressionTypePB _compression_type = segment_v2::CompressionTypePB::LZ4F;
814
    long _row_store_page_size = segment_v2::ROW_STORE_PAGE_SIZE_DEFAULT_VALUE;
815
    long _storage_page_size = segment_v2::STORAGE_PAGE_SIZE_DEFAULT_VALUE;
816
    long _storage_dict_page_size = segment_v2::STORAGE_DICT_PAGE_SIZE_DEFAULT_VALUE;
817
    size_t _next_column_unique_id = 0;
818
    std::string _auto_increment_column;
819
820
    bool _has_bf_fpp = false;
821
    double _bf_fpp = 0;
822
    bool _is_in_memory = false;
823
    int32_t _delete_sign_idx = -1;
824
    int32_t _sequence_col_idx = -1;
825
    int32_t _version_col_idx = -1;
826
    int32_t _skip_bitmap_col_idx = -1;
827
    int32_t _commit_tso_col_idx = -1;
828
    int32_t _row_lsn_col_idx = -1;
829
    int32_t _binlog_tso_col_idx = -1;
830
    int32_t _binlog_lsn_col_idx = -1;
831
    int32_t _binlog_op_col_idx = -1;
832
    int32_t _schema_version = -1;
833
    int64_t _table_id = -1;
834
    int64_t _db_id = -1;
835
    bool _disable_auto_compaction = false;
836
    bool _store_row_column = false;
837
    bool _skip_write_index_on_load = false;
838
    InvertedIndexStorageFormatPB _inverted_index_storage_format = InvertedIndexStorageFormatPB::V1;
839
840
    // Contains column ids of which columns should be encoded into row store.
841
    // ATTN: For compability reason empty cids means all columns of tablet schema are encoded to row column
842
    std::vector<int32_t> _row_store_column_unique_ids;
843
    bool _deprecated_enable_variant_flatten_nested = false;
844
845
    std::map<size_t, int32_t> _vir_col_idx_to_unique_id;
846
847
    // value: extracted path set and sparse path set
848
    std::unordered_map<int32_t, PathsSetInfo> _path_set_info_map;
849
850
    // key: field_pattern
851
    // value: indexes
852
    using PatternToIndex = std::unordered_map<std::string, std::vector<TabletIndexPtr>>;
853
    std::unordered_map<int32_t, PatternToIndex> _index_by_unique_id_with_pattern;
854
855
    // Default behavior for new segments: use external ColumnMeta region + CMO table if true
856
    // Persisted tablet storage format. Authoritative source for "is this tablet V3?"
857
    // decisions in the segment write paths. Old PBs without this field are upgraded in
858
    // init_from_pb() by deriving V3 from any of the three legacy V3-flavor flags.
859
    TabletStorageFormatPB _storage_format {TabletStorageFormatPB::TABLET_STORAGE_FORMAT_V2};
860
    // Sequence column unique id mapping to value columns unique id
861
    std::unordered_map<uint32_t, std::vector<uint32_t>> _seq_col_uid_to_value_cols_uid;
862
    // Value column unique id mapping to sequence column unique id(also map sequence column it self)
863
    std::unordered_map<uint32_t, uint32_t> _value_col_uid_to_seq_col_uid;
864
    // Sequence column index mapping to value column index
865
    std::unordered_map<uint32_t, std::vector<uint32_t>> _seq_col_idx_to_value_cols_idx;
866
};
867
868
bool operator==(const TabletSchema& a, const TabletSchema& b);
869
bool operator!=(const TabletSchema& a, const TabletSchema& b);
870
871
using TabletSchemaSPtr = std::shared_ptr<TabletSchema>;
872
873
} // namespace doris