Coverage Report

Created: 2026-05-18 00:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/common/variant_util.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "exec/common/variant_util.h"
19
20
#include <assert.h>
21
#include <fmt/format.h>
22
#include <gen_cpp/FrontendService.h>
23
#include <gen_cpp/FrontendService_types.h>
24
#include <gen_cpp/HeartbeatService_types.h>
25
#include <gen_cpp/MasterService_types.h>
26
#include <gen_cpp/Status_types.h>
27
#include <gen_cpp/Types_types.h>
28
#include <glog/logging.h>
29
#include <rapidjson/document.h>
30
#include <rapidjson/stringbuffer.h>
31
#include <rapidjson/writer.h>
32
#include <simdjson/simdjson.h> // IWYU pragma: keep
33
#include <unicode/uchar.h>
34
35
#include <algorithm>
36
#include <cassert>
37
#include <cstddef>
38
#include <cstdint>
39
#include <cstring>
40
#include <list>
41
#include <memory>
42
#include <mutex>
43
#include <optional>
44
#include <ostream>
45
#include <ranges>
46
#include <set>
47
#include <stack>
48
#include <string>
49
#include <string_view>
50
#include <unordered_map>
51
#include <utility>
52
#include <vector>
53
54
#include "common/config.h"
55
#include "common/status.h"
56
#include "core/assert_cast.h"
57
#include "core/block/block.h"
58
#include "core/block/column_numbers.h"
59
#include "core/block/column_with_type_and_name.h"
60
#include "core/column/column.h"
61
#include "core/column/column_array.h"
62
#include "core/column/column_map.h"
63
#include "core/column/column_nullable.h"
64
#include "core/column/column_string.h"
65
#include "core/column/column_variant.h"
66
#include "core/data_type/data_type.h"
67
#include "core/data_type/data_type_array.h"
68
#include "core/data_type/data_type_factory.hpp"
69
#include "core/data_type/data_type_jsonb.h"
70
#include "core/data_type/data_type_nullable.h"
71
#include "core/data_type/data_type_string.h"
72
#include "core/data_type/data_type_variant.h"
73
#include "core/data_type/define_primitive_type.h"
74
#include "core/data_type/get_least_supertype.h"
75
#include "core/data_type/primitive_type.h"
76
#include "core/field.h"
77
#include "core/typeid_cast.h"
78
#include "core/types.h"
79
#include "exec/common/field_visitors.h"
80
#include "exec/common/sip_hash.h"
81
#include "exprs/function/function.h"
82
#include "exprs/function/simple_function_factory.h"
83
#include "exprs/function_context.h"
84
#include "exprs/json_functions.h"
85
#include "re2/re2.h"
86
#include "runtime/exec_env.h"
87
#include "runtime/runtime_state.h"
88
#include "storage/olap_common.h"
89
#include "storage/rowset/beta_rowset.h"
90
#include "storage/rowset/rowset.h"
91
#include "storage/rowset/rowset_fwd.h"
92
#include "storage/segment/segment_loader.h"
93
#include "storage/segment/variant/nested_group_path.h"
94
#include "storage/segment/variant/variant_column_reader.h"
95
#include "storage/segment/variant/variant_column_writer_impl.h"
96
#include "storage/tablet/tablet.h"
97
#include "storage/tablet/tablet_fwd.h"
98
#include "storage/tablet/tablet_schema.h"
99
#include "util/client_cache.h"
100
#include "util/defer_op.h"
101
#include "util/json/json_parser.h"
102
#include "util/json/path_in_data.h"
103
#include "util/json/simd_json_parser.h"
104
105
namespace doris::variant_util {
106
107
10
static bool is_decimal_typed_path_column(const TabletColumn& column) {
108
10
    if (column.is_array_type()) {
109
0
        CHECK_EQ(column.get_sub_columns().size(), 1);
110
0
        return is_decimal_typed_path_column(*column.get_sub_columns()[0]);
111
0
    }
112
10
    return is_decimal(TabletColumn::get_primitive_type_by_field_type(column.type()));
113
10
}
114
115
static void configure_decimal_number_preserve_paths(const TabletColumn& column,
116
277
                                                    ParseConfig* config) {
117
277
    std::vector<std::string> glob_patterns;
118
277
    for (const auto& sub_column : column.get_sub_columns()) {
119
10
        if (!is_decimal_typed_path_column(*sub_column)) {
120
10
            continue;
121
10
        }
122
0
        switch (sub_column->pattern_type()) {
123
0
        case PatternTypePB::MATCH_NAME:
124
0
            config->preserve_decimal_number_paths.emplace(sub_column->name());
125
0
            break;
126
0
        case PatternTypePB::MATCH_NAME_GLOB:
127
0
            glob_patterns.emplace_back(sub_column->name());
128
0
            break;
129
0
        }
130
0
    }
131
277
    if (!glob_patterns.empty()) {
132
0
        config->preserve_decimal_number_path_matcher =
133
0
                [glob_patterns = std::move(glob_patterns)](std::string_view path) {
134
0
                    std::string candidate_path(path);
135
0
                    for (const auto& pattern : glob_patterns) {
136
0
                        if (glob_match_re2(pattern, candidate_path)) {
137
0
                            return true;
138
0
                        }
139
0
                    }
140
0
                    return false;
141
0
                };
142
0
    }
143
277
}
144
145
232
inline void append_escaped_regex_char(std::string* regex_output, char ch) {
146
232
    switch (ch) {
147
11
    case '.':
148
13
    case '^':
149
15
    case '$':
150
17
    case '+':
151
22
    case '*':
152
24
    case '?':
153
26
    case '(':
154
28
    case ')':
155
30
    case '|':
156
32
    case '{':
157
34
    case '}':
158
36
    case '[':
159
36
    case ']':
160
40
    case '\\':
161
40
        regex_output->push_back('\\');
162
40
        regex_output->push_back(ch);
163
40
        break;
164
192
    default:
165
192
        regex_output->push_back(ch);
166
192
        break;
167
232
    }
168
232
}
169
170
// Small LRU to cap compiled glob patterns
171
constexpr size_t kGlobRegexCacheCapacity = 256;
172
173
struct GlobRegexCacheEntry {
174
    std::shared_ptr<RE2> re2;
175
    std::list<std::string>::iterator lru_it;
176
};
177
178
static std::mutex g_glob_regex_cache_mutex;
179
static std::list<std::string> g_glob_regex_cache_lru;
180
static std::unordered_map<std::string, GlobRegexCacheEntry> g_glob_regex_cache;
181
182
174
std::shared_ptr<RE2> get_or_build_re2(const std::string& glob_pattern) {
183
174
    {
184
174
        std::lock_guard<std::mutex> lock(g_glob_regex_cache_mutex);
185
174
        auto it = g_glob_regex_cache.find(glob_pattern);
186
174
        if (it != g_glob_regex_cache.end()) {
187
126
            g_glob_regex_cache_lru.splice(g_glob_regex_cache_lru.begin(), g_glob_regex_cache_lru,
188
126
                                          it->second.lru_it);
189
126
            return it->second.re2;
190
126
        }
191
174
    }
192
48
    std::string regex_pattern;
193
48
    Status st = glob_to_regex(glob_pattern, &regex_pattern);
194
48
    if (!st.ok()) {
195
2
        return nullptr;
196
2
    }
197
46
    auto compiled = std::make_shared<RE2>(regex_pattern);
198
46
    if (!compiled->ok()) {
199
3
        return nullptr;
200
3
    }
201
43
    {
202
43
        std::lock_guard<std::mutex> lock(g_glob_regex_cache_mutex);
203
43
        auto it = g_glob_regex_cache.find(glob_pattern);
204
43
        if (it != g_glob_regex_cache.end()) {
205
0
            g_glob_regex_cache_lru.splice(g_glob_regex_cache_lru.begin(), g_glob_regex_cache_lru,
206
0
                                          it->second.lru_it);
207
0
            return it->second.re2;
208
0
        }
209
43
        g_glob_regex_cache_lru.push_front(glob_pattern);
210
43
        g_glob_regex_cache.emplace(glob_pattern,
211
43
                                   GlobRegexCacheEntry {compiled, g_glob_regex_cache_lru.begin()});
212
43
        if (g_glob_regex_cache.size() > kGlobRegexCacheCapacity) {
213
0
            const std::string& evict_key = g_glob_regex_cache_lru.back();
214
0
            g_glob_regex_cache.erase(evict_key);
215
0
            g_glob_regex_cache_lru.pop_back();
216
0
        }
217
43
    }
218
0
    return compiled;
219
43
}
220
221
// Convert a restricted glob pattern into a regex.
222
// Supported: '*', '?', '[...]', '\\' escape. Others are treated as literals.
223
86
Status glob_to_regex(const std::string& glob_pattern, std::string* regex_pattern) {
224
86
    regex_pattern->clear();
225
86
    regex_pattern->append("^");
226
86
    bool is_escaped = false;
227
86
    size_t pattern_length = glob_pattern.size();
228
384
    for (size_t index = 0; index < pattern_length; ++index) {
229
302
        char current_char = glob_pattern[index];
230
302
        if (is_escaped) {
231
9
            append_escaped_regex_char(regex_pattern, current_char);
232
9
            is_escaped = false;
233
9
            continue;
234
9
        }
235
293
        if (current_char == '\\') {
236
13
            is_escaped = true;
237
13
            continue;
238
13
        }
239
280
        if (current_char == '*') {
240
16
            regex_pattern->append(".*");
241
16
            continue;
242
16
        }
243
264
        if (current_char == '?') {
244
13
            regex_pattern->append(".");
245
13
            continue;
246
13
        }
247
251
        if (current_char == '[') {
248
32
            size_t class_index = index + 1;
249
32
            bool class_closed = false;
250
32
            bool is_class_escaped = false;
251
32
            std::string class_buffer;
252
32
            if (class_index < pattern_length &&
253
32
                (glob_pattern[class_index] == '!' || glob_pattern[class_index] == '^')) {
254
9
                class_buffer.push_back('^');
255
9
                ++class_index;
256
9
            }
257
95
            for (; class_index < pattern_length; ++class_index) {
258
91
                char class_char = glob_pattern[class_index];
259
91
                if (is_class_escaped) {
260
10
                    class_buffer.push_back(class_char);
261
10
                    is_class_escaped = false;
262
10
                    continue;
263
10
                }
264
81
                if (class_char == '\\') {
265
10
                    is_class_escaped = true;
266
10
                    continue;
267
10
                }
268
71
                if (class_char == ']') {
269
28
                    class_closed = true;
270
28
                    break;
271
28
                }
272
43
                class_buffer.push_back(class_char);
273
43
            }
274
32
            if (!class_closed) {
275
4
                return Status::InvalidArgument("Unclosed character class in glob pattern: {}",
276
4
                                               glob_pattern);
277
4
            }
278
28
            regex_pattern->append("[");
279
28
            regex_pattern->append(class_buffer);
280
28
            regex_pattern->append("]");
281
28
            index = class_index;
282
28
            continue;
283
32
        }
284
219
        append_escaped_regex_char(regex_pattern, current_char);
285
219
    }
286
82
    if (is_escaped) {
287
4
        append_escaped_regex_char(regex_pattern, '\\');
288
4
    }
289
82
    regex_pattern->append("$");
290
82
    return Status::OK();
291
86
}
292
293
174
bool glob_match_re2(const std::string& glob_pattern, const std::string& candidate_path) {
294
174
    auto compiled = get_or_build_re2(glob_pattern);
295
174
    if (compiled == nullptr) {
296
5
        return false;
297
5
    }
298
169
    return RE2::FullMatch(candidate_path, *compiled);
299
174
}
300
301
// NestedGroup's physical children and offsets are produced by NestedGroupWriteProvider, not by
302
// appending TabletSchema extracted columns here. This predicate keeps only ordinary Variant paths
303
// that are outside the NG tree, for example `v.owner` beside `v.items[*]`.
304
0
bool is_regular_path_outside_nested_group(const PathInData& path) {
305
0
    const std::string& relative_path = path.get_path();
306
0
    return !relative_path.empty() && !path.get_is_typed() && !path.has_nested_part() &&
307
0
           !segment_v2::contains_nested_group_marker(relative_path) &&
308
0
           !segment_v2::is_root_nested_group_path(relative_path) &&
309
0
           relative_path != SPARSE_COLUMN_PATH &&
310
0
           relative_path.find(DOC_VALUE_COLUMN_PATH) == std::string::npos;
311
0
}
312
313
bool should_materialize_nested_group_regular_subcolumns(
314
        const TabletColumnPtr& column,
315
7
        const std::unordered_map<int32_t, VariantExtendedInfo>& uid_to_variant_extended_info) {
316
7
    const auto info_it = uid_to_variant_extended_info.find(column->unique_id());
317
7
    return column->variant_enable_nested_group() ||
318
7
           (info_it != uid_to_variant_extended_info.end() && info_it->second.has_nested_group);
319
7
}
320
321
std::unordered_set<int32_t> collect_nested_group_compaction_root_uids(
322
        const TabletSchemaSPtr& target,
323
41
        const std::unordered_map<int32_t, VariantExtendedInfo>& uid_to_variant_extended_info) {
324
41
    std::unordered_set<int32_t> root_uids;
325
828
    for (const TabletColumnPtr& column : target->columns()) {
326
828
        if (column->is_variant_type() && should_materialize_nested_group_regular_subcolumns(
327
7
                                                 column, uid_to_variant_extended_info)) {
328
1
            root_uids.insert(column->unique_id());
329
1
        }
330
828
    }
331
41
    return root_uids;
332
41
}
333
334
PathToDataTypes collect_regular_types_outside_nested_group(
335
1
        const VariantExtendedInfo& extended_info) {
336
1
    PathToDataTypes regular_path_to_data_types;
337
1
    for (const auto& [path, data_types] : extended_info.path_to_data_types) {
338
0
        if (!is_regular_path_outside_nested_group(path)) {
339
0
            continue;
340
0
        }
341
0
        regular_path_to_data_types.emplace(path, data_types);
342
0
    }
343
1
    return regular_path_to_data_types;
344
1
}
345
346
14
size_t get_number_of_dimensions(const IDataType& type) {
347
14
    if (const auto* type_array = typeid_cast<const DataTypeArray*>(&type)) {
348
4
        return type_array->get_number_of_dimensions();
349
4
    }
350
10
    return 0;
351
14
}
352
3
size_t get_number_of_dimensions(const IColumn& column) {
353
3
    if (const auto* column_array = check_and_get_column<ColumnArray>(column)) {
354
2
        return column_array->get_number_of_dimensions();
355
2
    }
356
1
    return 0;
357
3
}
358
359
980
DataTypePtr get_base_type_of_array(const DataTypePtr& type) {
360
    /// Get raw pointers to avoid extra copying of type pointers.
361
980
    const DataTypeArray* last_array = nullptr;
362
980
    const auto* current_type = type.get();
363
980
    if (const auto* nullable = typeid_cast<const DataTypeNullable*>(current_type)) {
364
976
        current_type = nullable->get_nested_type().get();
365
976
    }
366
998
    while (const auto* type_array = typeid_cast<const DataTypeArray*>(current_type)) {
367
18
        current_type = type_array->get_nested_type().get();
368
18
        last_array = type_array;
369
18
        if (const auto* nullable = typeid_cast<const DataTypeNullable*>(current_type)) {
370
12
            current_type = nullable->get_nested_type().get();
371
12
        }
372
18
    }
373
980
    return last_array ? last_array->get_nested_type() : type;
374
980
}
375
376
49.1k
Status cast_column(const ColumnWithTypeAndName& arg, const DataTypePtr& type, ColumnPtr* result) {
377
49.1k
    ColumnsWithTypeAndName arguments {arg, {nullptr, type, type->get_name()}};
378
379
    // To prevent from null info lost, we should not call function since the function framework will wrap
380
    // nullable to Variant instead of the root of Variant
381
    // correct output: Nullable(Array(int)) -> Nullable(Variant(Nullable(Array(int))))
382
    // incorrect output: Nullable(Array(int)) -> Nullable(Variant(Array(int)))
383
49.1k
    if (type->get_primitive_type() == TYPE_VARIANT) {
384
        // If source column is variant, so the nullable info is different from dst column
385
3
        if (arg.type->get_primitive_type() == TYPE_VARIANT) {
386
1
            *result = type->is_nullable() ? make_nullable(arg.column) : remove_nullable(arg.column);
387
1
            return Status::OK();
388
1
        }
389
        // set variant root column/type to from column/type
390
3
        CHECK(arg.column->is_nullable());
391
2
        auto to_type = remove_nullable(type);
392
2
        const auto& data_type_object = assert_cast<const DataTypeVariant&>(*to_type);
393
2
        auto variant = ColumnVariant::create(data_type_object.variant_max_subcolumns_count(),
394
2
                                             data_type_object.enable_doc_mode());
395
396
2
        variant->create_root(arg.type, arg.column->assume_mutable());
397
2
        ColumnPtr nullable = ColumnNullable::create(
398
2
                variant->get_ptr(),
399
2
                assert_cast<const ColumnNullable*>(arg.column.get())->get_null_map_column_ptr());
400
2
        *result = type->is_nullable() ? nullable : variant->get_ptr();
401
2
        return Status::OK();
402
3
    }
403
404
49.1k
    auto function = SimpleFunctionFactory::instance().get_function("CAST", arguments, type);
405
49.1k
    if (!function) {
406
0
        return Status::InternalError("Not found cast function {} to {}", arg.type->get_name(),
407
0
                                     type->get_name());
408
0
    }
409
49.1k
    Block tmp_block {arguments};
410
49.1k
    uint32_t result_column = cast_set<uint32_t>(tmp_block.columns());
411
49.1k
    RuntimeState state;
412
49.1k
    auto ctx = FunctionContext::create_context(&state, {}, {});
413
414
49.1k
    if (arg.type->get_primitive_type() == INVALID_TYPE) {
415
        // cast from nothing to any type should result in nulls
416
659
        *result = type->create_column_const_with_default_value(arg.column->size())
417
659
                          ->convert_to_full_column_if_const();
418
659
        return Status::OK();
419
659
    }
420
421
    // We convert column string to jsonb type just add a string jsonb field to dst column instead of parse
422
    // each line in original string column.
423
48.4k
    ctx->set_string_as_jsonb_string(true);
424
48.4k
    ctx->set_jsonb_string_as_string(true);
425
48.4k
    tmp_block.insert({nullptr, type, arg.name});
426
    // TODO(lihangyu): we should handle this error in strict mode
427
48.4k
    if (!function->execute(ctx.get(), tmp_block, {0}, result_column, arg.column->size())) {
428
0
        LOG_EVERY_N(WARNING, 100) << fmt::format("cast from {} to {}", arg.type->get_name(),
429
0
                                                 type->get_name());
430
0
        *result = type->create_column_const_with_default_value(arg.column->size())
431
0
                          ->convert_to_full_column_if_const();
432
0
        return Status::OK();
433
0
    }
434
48.4k
    *result = tmp_block.get_by_position(result_column).column->convert_to_full_column_if_const();
435
48.4k
    VLOG_DEBUG << fmt::format("{} before convert {}, after convert {}", arg.name,
436
0
                              arg.column->get_name(), (*result)->get_name());
437
48.4k
    return Status::OK();
438
48.4k
}
439
440
void get_column_by_type(const DataTypePtr& data_type, const std::string& name, TabletColumn& column,
441
2.01k
                        const ExtraInfo& ext_info) {
442
2.01k
    column.set_name(name);
443
2.01k
    column.set_type(data_type->get_storage_field_type());
444
2.01k
    if (ext_info.unique_id >= 0) {
445
4
        column.set_unique_id(ext_info.unique_id);
446
4
    }
447
2.01k
    if (ext_info.parent_unique_id >= 0) {
448
1.00k
        column.set_parent_unique_id(ext_info.parent_unique_id);
449
1.00k
    }
450
2.01k
    if (!ext_info.path_info.empty()) {
451
1.00k
        column.set_path_info(ext_info.path_info);
452
1.00k
    }
453
2.01k
    if (data_type->is_nullable()) {
454
998
        const auto& real_type = static_cast<const DataTypeNullable&>(*data_type);
455
998
        column.set_is_nullable(true);
456
998
        get_column_by_type(real_type.get_nested_type(), name, column, {});
457
998
        return;
458
998
    }
459
1.02k
    if (data_type->get_primitive_type() == PrimitiveType::TYPE_ARRAY) {
460
13
        TabletColumn child;
461
13
        get_column_by_type(assert_cast<const DataTypeArray*>(data_type.get())->get_nested_type(),
462
13
                           "", child, {});
463
13
        column.set_length(TabletColumn::get_field_length_by_type(TPrimitiveType::ARRAY, 0));
464
13
        column.add_sub_column(child);
465
13
        return;
466
13
    }
467
1.00k
    if (data_type->get_primitive_type() == PrimitiveType::TYPE_VARIANT) {
468
0
        const auto* dt_variant = assert_cast<const DataTypeVariant*>(data_type.get());
469
0
        column.set_variant_max_subcolumns_count(dt_variant->variant_max_subcolumns_count());
470
0
        column.set_variant_enable_doc_mode(dt_variant->enable_doc_mode());
471
0
        return;
472
0
    }
473
    // size is not fixed when type is string or json
474
1.00k
    if (is_string_type(data_type->get_primitive_type()) ||
475
1.00k
        data_type->get_primitive_type() == TYPE_JSONB) {
476
366
        column.set_length(INT_MAX);
477
366
        return;
478
366
    }
479
480
641
    PrimitiveType type = data_type->get_primitive_type();
481
641
    if (is_int_or_bool(type) || is_string_type(type) || is_float_or_double(type) || is_ip(type) ||
482
641
        is_date_or_datetime(type) || type == PrimitiveType::TYPE_DATEV2) {
483
638
        column.set_length(cast_set<int32_t>(data_type->get_size_of_value_in_memory()));
484
638
        return;
485
638
    }
486
3
    if (is_decimal(type)) {
487
1
        column.set_precision(data_type->get_precision());
488
1
        column.set_frac(data_type->get_scale());
489
1
        return;
490
1
    }
491
    // datetimev2 needs scale
492
2
    if (type == PrimitiveType::TYPE_DATETIMEV2 || type == PrimitiveType::TYPE_TIMESTAMPTZ) {
493
1
        column.set_precision(-1);
494
1
        column.set_frac(data_type->get_scale());
495
1
        return;
496
1
    }
497
498
1
    throw doris::Exception(doris::ErrorCode::INTERNAL_ERROR,
499
1
                           "unexcepted data column type: {}, column name is: {}",
500
1
                           data_type->get_name(), name);
501
2
}
502
503
TabletColumn get_column_by_type(const DataTypePtr& data_type, const std::string& name,
504
1.00k
                                const ExtraInfo& ext_info) {
505
1.00k
    TabletColumn result;
506
1.00k
    get_column_by_type(data_type, name, result, ext_info);
507
1.00k
    return result;
508
1.00k
}
509
510
// check if two paths which same prefix have different structure
511
static bool has_different_structure_in_same_path(const PathInData::Parts& lhs,
512
9.00k
                                                 const PathInData::Parts& rhs) {
513
9.00k
    if (lhs.size() != rhs.size()) {
514
1
        return false; // different size means different structure
515
1
    }
516
    // Since we group by path string, lhs and rhs must have the same size and keys
517
    // We only need to check if they have different nested structure
518
35.9k
    for (size_t i = 0; i < lhs.size(); ++i) {
519
26.9k
        if (lhs[i] != rhs[i]) {
520
5
            VLOG_DEBUG << fmt::format(
521
0
                    "Check different structure: {} vs {}, lhs[i].is_nested: {}, rhs[i].is_nested: "
522
0
                    "{}",
523
0
                    lhs[i].key, rhs[i].key, lhs[i].is_nested, rhs[i].is_nested);
524
5
            return true;
525
5
        }
526
26.9k
    }
527
8.99k
    return false;
528
8.99k
}
529
530
3.02k
Status check_variant_has_no_ambiguous_paths(const PathsInData& tuple_paths) {
531
    // Group paths by their string representation to reduce comparisons
532
3.02k
    std::unordered_map<std::string, std::vector<size_t>> path_groups;
533
534
24.0k
    for (size_t i = 0; i < tuple_paths.size(); ++i) {
535
        // same path should have same structure, so we group them by path
536
21.0k
        path_groups[tuple_paths[i].get_path()].push_back(i);
537
        // print part of tuple_paths[i]
538
21.0k
        VLOG_DEBUG << "tuple_paths[i]: " << tuple_paths[i].get_path();
539
21.0k
    }
540
541
    // Only compare paths within the same group
542
12.0k
    for (const auto& [path_str, indices] : path_groups) {
543
12.0k
        if (indices.size() <= 1) {
544
3.02k
            continue; // No conflicts possible
545
3.02k
        }
546
547
        // Compare all pairs within this group
548
26.9k
        for (size_t i = 0; i < indices.size(); ++i) {
549
26.9k
            for (size_t j = 0; j < i; ++j) {
550
9.00k
                if (has_different_structure_in_same_path(tuple_paths[indices[i]].get_parts(),
551
9.00k
                                                         tuple_paths[indices[j]].get_parts())) {
552
5
                    return Status::DataQualityError(
553
5
                            "Ambiguous paths: {} vs {} with different nested part {} vs {}",
554
5
                            tuple_paths[indices[i]].get_path(), tuple_paths[indices[j]].get_path(),
555
5
                            tuple_paths[indices[i]].has_nested_part(),
556
5
                            tuple_paths[indices[j]].has_nested_part());
557
5
                }
558
9.00k
            }
559
18.0k
        }
560
9.00k
    }
561
3.01k
    return Status::OK();
562
3.02k
}
563
564
Status update_least_schema_internal(const std::map<PathInData, DataTypes>& subcolumns_types,
565
                                    TabletSchemaSPtr& common_schema, int32_t variant_col_unique_id,
566
                                    const std::map<std::string, TabletColumnPtr>& typed_columns,
567
8
                                    std::set<PathInData>* path_set) {
568
8
    PathsInData tuple_paths;
569
8
    DataTypes tuple_types;
570
8
    CHECK(common_schema.use_count() == 1);
571
    // Get the least common type for all paths.
572
8
    for (const auto& [key, subtypes] : subcolumns_types) {
573
7
        assert(!subtypes.empty());
574
7
        if (key.get_path() == ColumnVariant::COLUMN_NAME_DUMMY) {
575
0
            continue;
576
0
        }
577
7
        size_t first_dim = get_number_of_dimensions(*subtypes[0]);
578
7
        tuple_paths.emplace_back(key);
579
10
        for (size_t i = 1; i < subtypes.size(); ++i) {
580
4
            if (first_dim != get_number_of_dimensions(*subtypes[i])) {
581
1
                tuple_types.emplace_back(make_nullable(std::make_shared<DataTypeJsonb>()));
582
1
                LOG(INFO) << fmt::format(
583
1
                        "Uncompatible types of subcolumn '{}': {} and {}, cast to JSONB",
584
1
                        key.get_path(), subtypes[0]->get_name(), subtypes[i]->get_name());
585
1
                break;
586
1
            }
587
4
        }
588
7
        if (tuple_paths.size() == tuple_types.size()) {
589
1
            continue;
590
1
        }
591
6
        DataTypePtr common_type;
592
6
        get_least_supertype_jsonb(subtypes, &common_type);
593
6
        if (!common_type->is_nullable()) {
594
3
            common_type = make_nullable(common_type);
595
3
        }
596
6
        tuple_types.emplace_back(common_type);
597
6
    }
598
8
    CHECK_EQ(tuple_paths.size(), tuple_types.size());
599
600
    // Append all common type columns of this variant
601
15
    for (int i = 0; i < tuple_paths.size(); ++i) {
602
7
        TabletColumn common_column;
603
        // typed path not contains root part
604
7
        auto path_without_root = tuple_paths[i].copy_pop_front().get_path();
605
7
        if (typed_columns.contains(path_without_root) && !tuple_paths[i].has_nested_part()) {
606
0
            common_column = *typed_columns.at(path_without_root);
607
            // parent unique id and path may not be init in write path
608
0
            common_column.set_parent_unique_id(variant_col_unique_id);
609
0
            common_column.set_path_info(tuple_paths[i]);
610
0
            common_column.set_name(tuple_paths[i].get_path());
611
7
        } else {
612
            // const std::string& column_name = variant_col_name + "." + tuple_paths[i].get_path();
613
7
            get_column_by_type(tuple_types[i], tuple_paths[i].get_path(), common_column,
614
7
                               ExtraInfo {.unique_id = -1,
615
7
                                          .parent_unique_id = variant_col_unique_id,
616
7
                                          .path_info = tuple_paths[i]});
617
7
        }
618
7
        common_schema->append_column(common_column);
619
7
        if (path_set != nullptr) {
620
4
            path_set->insert(tuple_paths[i]);
621
4
        }
622
7
    }
623
8
    return Status::OK();
624
8
}
625
626
Status update_least_common_schema(const std::vector<TabletSchemaSPtr>& schemas,
627
                                  TabletSchemaSPtr& common_schema, int32_t variant_col_unique_id,
628
7
                                  std::set<PathInData>* path_set) {
629
7
    std::map<std::string, TabletColumnPtr> typed_columns;
630
7
    for (const TabletColumnPtr& col :
631
7
         common_schema->column_by_uid(variant_col_unique_id).get_sub_columns()) {
632
2
        typed_columns[col->name()] = col;
633
2
    }
634
    // Types of subcolumns by path from all tuples.
635
7
    std::map<PathInData, DataTypes> subcolumns_types;
636
637
    // Collect all paths first to enable batch checking
638
7
    std::vector<PathInData> all_paths;
639
640
12
    for (const TabletSchemaSPtr& schema : schemas) {
641
16
        for (const TabletColumnPtr& col : schema->columns()) {
642
            // Get subcolumns of this variant
643
16
            if (col->has_path_info() && col->parent_unique_id() >= 0 &&
644
16
                col->parent_unique_id() == variant_col_unique_id) {
645
6
                subcolumns_types[*col->path_info_ptr()].emplace_back(
646
6
                        DataTypeFactory::instance().create_data_type(*col, col->is_nullable()));
647
6
                all_paths.push_back(*col->path_info_ptr());
648
6
            }
649
16
        }
650
12
    }
651
652
    // Batch check for conflicts
653
7
    RETURN_IF_ERROR(check_variant_has_no_ambiguous_paths(all_paths));
654
655
7
    return update_least_schema_internal(subcolumns_types, common_schema, variant_col_unique_id,
656
7
                                        typed_columns, path_set);
657
7
}
658
659
// Keep variant subcolumn BF support aligned with FE DDL checks.
660
1.01k
bool is_bf_supported_by_fe_for_variant_subcolumn(FieldType type) {
661
1.01k
    switch (type) {
662
0
    case FieldType::OLAP_FIELD_TYPE_SMALLINT:
663
7
    case FieldType::OLAP_FIELD_TYPE_INT:
664
628
    case FieldType::OLAP_FIELD_TYPE_BIGINT:
665
628
    case FieldType::OLAP_FIELD_TYPE_LARGEINT:
666
628
    case FieldType::OLAP_FIELD_TYPE_CHAR:
667
628
    case FieldType::OLAP_FIELD_TYPE_VARCHAR:
668
993
    case FieldType::OLAP_FIELD_TYPE_STRING:
669
993
    case FieldType::OLAP_FIELD_TYPE_DATE:
670
993
    case FieldType::OLAP_FIELD_TYPE_DATETIME:
671
1.00k
    case FieldType::OLAP_FIELD_TYPE_DATEV2:
672
1.00k
    case FieldType::OLAP_FIELD_TYPE_DATETIMEV2:
673
1.00k
    case FieldType::OLAP_FIELD_TYPE_TIMESTAMPTZ:
674
1.00k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL:
675
1.00k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL32:
676
1.00k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL64:
677
1.00k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL128I:
678
1.00k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL256:
679
1.00k
    case FieldType::OLAP_FIELD_TYPE_IPV4:
680
1.00k
    case FieldType::OLAP_FIELD_TYPE_IPV6:
681
1.00k
        return true;
682
16
    default:
683
16
        return false;
684
1.01k
    }
685
1.01k
}
686
687
void inherit_column_attributes(const TabletColumn& source, TabletColumn& target,
688
1.01k
                               TabletSchemaSPtr* target_schema) {
689
1.01k
    if (!target.is_extracted_column()) {
690
0
        return;
691
0
    }
692
1.01k
    target.set_aggregation_method(source.aggregation());
693
694
    // 1. bloom filter
695
1.01k
    if (is_bf_supported_by_fe_for_variant_subcolumn(target.type())) {
696
1.00k
        target.set_is_bf_column(source.is_bf_column());
697
1.00k
    }
698
699
1.01k
    if (!target_schema) {
700
1.00k
        return;
701
1.00k
    }
702
703
    // 2. inverted index
704
8
    TabletIndexes indexes_to_add;
705
8
    auto source_indexes = (*target_schema)->inverted_indexs(source.unique_id());
706
    // if target is variant type, we need to inherit all indexes
707
    // because this schema is a read schema from fe
708
8
    if (target.is_variant_type()) {
709
0
        for (auto& index : source_indexes) {
710
0
            auto index_info = std::make_shared<TabletIndex>(*index);
711
0
            index_info->set_escaped_escaped_index_suffix_path(target.path_info_ptr()->get_path());
712
0
            indexes_to_add.emplace_back(std::move(index_info));
713
0
        }
714
8
    } else {
715
8
        inherit_index(source_indexes, indexes_to_add, target);
716
8
    }
717
8
    auto target_indexes = (*target_schema)
718
8
                                  ->inverted_indexs(target.parent_unique_id(),
719
8
                                                    target.path_info_ptr()->get_path());
720
8
    if (target_indexes.empty()) {
721
8
        for (auto& index_info : indexes_to_add) {
722
8
            (*target_schema)->append_index(std::move(*index_info));
723
8
        }
724
8
    }
725
726
    // 3. TODO: gnragm bf index
727
8
}
728
729
6
void inherit_column_attributes(TabletSchemaSPtr& schema) {
730
    // Add index meta if extracted column is missing index meta
731
23
    for (size_t i = 0; i < schema->num_columns(); ++i) {
732
17
        TabletColumn& col = schema->mutable_column(i);
733
17
        if (!col.is_extracted_column()) {
734
9
            continue;
735
9
        }
736
8
        if (schema->field_index(col.parent_unique_id()) == -1) {
737
            // parent column is missing, maybe dropped
738
0
            continue;
739
0
        }
740
8
        inherit_column_attributes(schema->column_by_uid(col.parent_unique_id()), col, &schema);
741
8
    }
742
6
}
743
744
Status get_least_common_schema(const std::vector<TabletSchemaSPtr>& schemas,
745
                               const TabletSchemaSPtr& base_schema, TabletSchemaSPtr& output_schema,
746
4
                               bool check_schema_size) {
747
4
    std::vector<int32_t> variant_column_unique_id;
748
    // Construct a schema excluding the extracted columns and gather unique identifiers for variants.
749
    // Ensure that the output schema also excludes these extracted columns. This approach prevents
750
    // duplicated paths following the update_least_common_schema process.
751
4
    auto build_schema_without_extracted_columns = [&](const TabletSchemaSPtr& base_schema) {
752
4
        output_schema = std::make_shared<TabletSchema>();
753
        // not copy columns but only shadow copy other attributes
754
4
        output_schema->shawdow_copy_without_columns(*base_schema);
755
        // Get all columns without extracted columns and collect variant col unique id
756
7
        for (const TabletColumnPtr& col : base_schema->columns()) {
757
7
            if (col->is_variant_type()) {
758
4
                variant_column_unique_id.push_back(col->unique_id());
759
4
            }
760
7
            if (!col->is_extracted_column()) {
761
4
                output_schema->append_column(*col);
762
4
            }
763
7
        }
764
4
    };
765
4
    if (base_schema == nullptr) {
766
        // Pick tablet schema with max schema version
767
4
        auto max_version_schema =
768
4
                *std::max_element(schemas.cbegin(), schemas.cend(),
769
4
                                  [](const TabletSchemaSPtr a, const TabletSchemaSPtr b) {
770
2
                                      return a->schema_version() < b->schema_version();
771
2
                                  });
772
4
        CHECK(max_version_schema);
773
4
        build_schema_without_extracted_columns(max_version_schema);
774
4
    } else {
775
        // use input base_schema schema as base schema
776
0
        build_schema_without_extracted_columns(base_schema);
777
0
    }
778
779
4
    for (int32_t unique_id : variant_column_unique_id) {
780
4
        std::set<PathInData> path_set;
781
4
        RETURN_IF_ERROR(update_least_common_schema(schemas, output_schema, unique_id, &path_set));
782
4
    }
783
784
4
    inherit_column_attributes(output_schema);
785
4
    if (check_schema_size &&
786
4
        output_schema->columns().size() > config::variant_max_merged_tablet_schema_size) {
787
0
        return Status::DataQualityError("Reached max column size limit {}",
788
0
                                        config::variant_max_merged_tablet_schema_size);
789
0
    }
790
791
4
    return Status::OK();
792
4
}
793
794
// sort by paths in lexicographical order
795
613
ColumnVariant::Subcolumns get_sorted_subcolumns(const ColumnVariant::Subcolumns& subcolumns) {
796
    // sort by paths in lexicographical order
797
613
    ColumnVariant::Subcolumns sorted = subcolumns;
798
3.93k
    std::sort(sorted.begin(), sorted.end(), [](const auto& lhsItem, const auto& rhsItem) {
799
3.93k
        return lhsItem->path < rhsItem->path;
800
3.93k
    });
801
613
    return sorted;
802
613
}
803
804
bool has_schema_index_diff(const TabletSchema* new_schema, const TabletSchema* old_schema,
805
4
                           int32_t new_col_idx, int32_t old_col_idx) {
806
4
    const auto& column_new = new_schema->column(new_col_idx);
807
4
    const auto& column_old = old_schema->column(old_col_idx);
808
809
4
    if (column_new.is_bf_column() != column_old.is_bf_column()) {
810
2
        return true;
811
2
    }
812
813
2
    auto new_schema_inverted_indexs = new_schema->inverted_indexs(column_new);
814
2
    auto old_schema_inverted_indexs = old_schema->inverted_indexs(column_old);
815
816
2
    if (new_schema_inverted_indexs.size() != old_schema_inverted_indexs.size()) {
817
1
        return true;
818
1
    }
819
820
2
    for (size_t i = 0; i < new_schema_inverted_indexs.size(); ++i) {
821
1
        if (!new_schema_inverted_indexs[i]->is_same_except_id(old_schema_inverted_indexs[i])) {
822
0
            return true;
823
0
        }
824
1
    }
825
826
1
    return false;
827
1
}
828
829
601
TabletColumn create_sparse_column(const TabletColumn& variant) {
830
601
    TabletColumn res;
831
601
    res.set_name(variant.name_lower_case() + "." + SPARSE_COLUMN_PATH);
832
601
    res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
833
601
    res.set_aggregation_method(variant.aggregation());
834
601
    res.set_path_info(PathInData {variant.name_lower_case() + "." + SPARSE_COLUMN_PATH});
835
601
    res.set_parent_unique_id(variant.unique_id());
836
    // set default value to "NULL" DefaultColumnIterator will call insert_many_defaults
837
601
    res.set_default_value("NULL");
838
601
    TabletColumn child_tcolumn;
839
601
    child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
840
601
    res.add_sub_column(child_tcolumn);
841
601
    res.add_sub_column(child_tcolumn);
842
601
    return res;
843
601
}
844
845
25
TabletColumn create_sparse_shard_column(const TabletColumn& variant, int bucket_index) {
846
25
    TabletColumn res;
847
25
    std::string name = variant.name_lower_case() + "." + SPARSE_COLUMN_PATH + ".b" +
848
25
                       std::to_string(bucket_index);
849
25
    res.set_name(name);
850
25
    res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
851
25
    res.set_aggregation_method(variant.aggregation());
852
25
    res.set_parent_unique_id(variant.unique_id());
853
25
    res.set_default_value("NULL");
854
25
    PathInData path(name);
855
25
    res.set_path_info(path);
856
25
    TabletColumn child_tcolumn;
857
25
    child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
858
25
    res.add_sub_column(child_tcolumn);
859
25
    res.add_sub_column(child_tcolumn);
860
25
    return res;
861
25
}
862
863
28
TabletColumn create_doc_value_column(const TabletColumn& variant, int bucket_index) {
864
28
    TabletColumn res;
865
28
    std::string name = variant.name_lower_case() + "." + DOC_VALUE_COLUMN_PATH + ".b" +
866
28
                       std::to_string(bucket_index);
867
28
    res.set_name(name);
868
28
    res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
869
28
    res.set_aggregation_method(variant.aggregation());
870
28
    res.set_parent_unique_id(variant.unique_id());
871
28
    res.set_default_value("NULL");
872
28
    res.set_path_info(PathInData {name});
873
874
28
    TabletColumn child_tcolumn;
875
28
    child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
876
28
    res.add_sub_column(child_tcolumn);
877
28
    res.add_sub_column(child_tcolumn);
878
28
    return res;
879
28
}
880
881
5.34k
uint32_t variant_binary_shard_of(const StringRef& path, uint32_t bucket_num) {
882
5.34k
    if (bucket_num <= 1) return 0;
883
5.34k
    SipHash hash;
884
5.34k
    hash.update(path.data, path.size);
885
5.34k
    uint64_t h = hash.get64();
886
5.34k
    return static_cast<uint32_t>(h % bucket_num);
887
5.34k
}
888
889
Status VariantCompactionUtil::aggregate_path_to_stats(
890
        const RowsetSharedPtr& rs,
891
19
        std::unordered_map<int32_t, PathToNoneNullValues>* uid_to_path_stats) {
892
19
    SegmentCacheHandle segment_cache;
893
19
    RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
894
19
            std::static_pointer_cast<BetaRowset>(rs), &segment_cache));
895
896
95
    for (const auto& column : rs->tablet_schema()->columns()) {
897
95
        if (!column->is_variant_type() || column->unique_id() < 0) {
898
57
            continue;
899
57
        }
900
38
        if (!should_check_variant_path_stats(*column)) {
901
0
            continue;
902
0
        }
903
178
        for (const auto& segment : segment_cache.get_segments()) {
904
178
            std::shared_ptr<ColumnReader> column_reader;
905
178
            OlapReaderStatistics stats;
906
178
            RETURN_IF_ERROR(
907
178
                    segment->get_column_reader(column->unique_id(), &column_reader, &stats));
908
178
            if (!column_reader) {
909
0
                continue;
910
0
            }
911
912
178
            CHECK(column_reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT);
913
178
            auto* variant_column_reader =
914
178
                    assert_cast<segment_v2::VariantColumnReader*>(column_reader.get());
915
            // load external meta before getting stats
916
178
            RETURN_IF_ERROR(variant_column_reader->load_external_meta_once());
917
178
            const auto* source_stats = variant_column_reader->get_stats();
918
178
            CHECK(source_stats);
919
920
            // agg path -> stats
921
1.24k
            for (const auto& [path, size] : source_stats->sparse_column_non_null_size) {
922
1.24k
                (*uid_to_path_stats)[column->unique_id()][path] += size;
923
1.24k
            }
924
925
524
            for (const auto& [path, size] : source_stats->subcolumns_non_null_size) {
926
524
                (*uid_to_path_stats)[column->unique_id()][path] += size;
927
524
            }
928
178
        }
929
38
    }
930
19
    return Status::OK();
931
19
}
932
933
Status VariantCompactionUtil::aggregate_variant_extended_info(
934
        const RowsetSharedPtr& rs,
935
10
        std::unordered_map<int32_t, VariantExtendedInfo>* uid_to_variant_extended_info) {
936
10
    SegmentCacheHandle segment_cache;
937
10
    RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
938
10
            std::static_pointer_cast<BetaRowset>(rs), &segment_cache));
939
940
34
    for (const auto& column : rs->tablet_schema()->columns()) {
941
34
        if (!column->is_variant_type()) {
942
18
            continue;
943
18
        }
944
16
        auto& extended_info = (*uid_to_variant_extended_info)[column->unique_id()];
945
16
        if (column->variant_enable_nested_group()) {
946
0
            extended_info.has_nested_group = true;
947
0
        }
948
62
        for (const auto& segment : segment_cache.get_segments()) {
949
62
            std::shared_ptr<ColumnReader> column_reader;
950
62
            OlapReaderStatistics stats;
951
62
            RETURN_IF_ERROR(
952
62
                    segment->get_column_reader(column->unique_id(), &column_reader, &stats));
953
62
            if (!column_reader) {
954
0
                continue;
955
0
            }
956
957
62
            CHECK(column_reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT);
958
62
            auto* variant_column_reader =
959
62
                    assert_cast<segment_v2::VariantColumnReader*>(column_reader.get());
960
            // load external meta before getting stats
961
62
            RETURN_IF_ERROR(variant_column_reader->load_external_meta_once());
962
62
            const auto* source_stats = variant_column_reader->get_stats();
963
62
            CHECK(source_stats);
964
965
62
            if (!column->variant_enable_nested_group()) {
966
                // NG roots still need type metadata for regular subpaths such as `v.owner`,
967
                // but their compaction schema should not be driven by flat path stats.
968
420
                for (const auto& [path, size] : source_stats->sparse_column_non_null_size) {
969
420
                    extended_info.path_to_none_null_values[path] += size;
970
420
                    extended_info.sparse_paths.emplace(path);
971
420
                }
972
973
174
                for (const auto& [path, size] : source_stats->subcolumns_non_null_size) {
974
174
                    extended_info.path_to_none_null_values[path] += size;
975
174
                }
976
62
            }
977
978
            //2. agg path -> schema
979
62
            variant_column_reader->get_subcolumns_types(&extended_info.path_to_data_types);
980
981
            // 3. extract typed paths
982
62
            variant_column_reader->get_typed_paths(&extended_info.typed_paths);
983
984
            // 4. extract nested paths
985
62
            if (!column->variant_enable_nested_group()) {
986
62
                variant_column_reader->get_nested_paths(&extended_info.nested_paths);
987
62
            }
988
62
        }
989
16
    }
990
10
    return Status::OK();
991
10
}
992
993
// get the subpaths and sparse paths for the variant column
994
void VariantCompactionUtil::get_subpaths(int32_t max_subcolumns_count,
995
                                         const PathToNoneNullValues& stats,
996
12
                                         TabletSchema::PathsSetInfo& paths_set_info) {
997
    // max_subcolumns_count is 0 means no limit
998
12
    if (max_subcolumns_count > 0 && stats.size() > max_subcolumns_count) {
999
6
        std::vector<std::pair<size_t, std::string_view>> paths_with_sizes;
1000
6
        paths_with_sizes.reserve(stats.size());
1001
48
        for (const auto& [path, size] : stats) {
1002
48
            paths_with_sizes.emplace_back(size, path);
1003
48
        }
1004
6
        std::sort(paths_with_sizes.begin(), paths_with_sizes.end(), std::greater());
1005
1006
        // Select top N paths as subcolumns, remaining paths as sparse columns
1007
48
        for (const auto& [size, path] : paths_with_sizes) {
1008
48
            if (paths_set_info.sub_path_set.size() < max_subcolumns_count) {
1009
18
                paths_set_info.sub_path_set.emplace(path);
1010
30
            } else {
1011
30
                paths_set_info.sparse_path_set.emplace(path);
1012
30
            }
1013
48
        }
1014
6
        LOG(INFO) << "subpaths " << paths_set_info.sub_path_set.size() << " sparse paths "
1015
6
                  << paths_set_info.sparse_path_set.size() << " variant max subcolumns count "
1016
6
                  << max_subcolumns_count << " stats size " << paths_with_sizes.size();
1017
6
    } else {
1018
        // Apply all paths as subcolumns
1019
13
        for (const auto& [path, _] : stats) {
1020
13
            paths_set_info.sub_path_set.emplace(path);
1021
13
        }
1022
6
    }
1023
12
}
1024
1025
Status VariantCompactionUtil::check_path_stats(const std::vector<RowsetSharedPtr>& intputs,
1026
11
                                               RowsetSharedPtr output, BaseTabletSPtr tablet) {
1027
11
    if (output->tablet_schema()->num_variant_columns() == 0) {
1028
6
        return Status::OK();
1029
6
    }
1030
26
    for (const auto& rowset : intputs) {
1031
130
        for (const auto& column : rowset->tablet_schema()->columns()) {
1032
130
            if (column->is_variant_type() && !should_check_variant_path_stats(*column)) {
1033
0
                return Status::OK();
1034
0
            }
1035
130
        }
1036
26
    }
1037
    // check no extended schema in input rowsets
1038
26
    for (const auto& rowset : intputs) {
1039
130
        for (const auto& column : rowset->tablet_schema()->columns()) {
1040
130
            if (column->is_extracted_column()) {
1041
0
                return Status::OK();
1042
0
            }
1043
130
        }
1044
26
    }
1045
#ifndef BE_TEST
1046
    // check no extended schema in output rowset
1047
    for (const auto& column : output->tablet_schema()->columns()) {
1048
        if (column->is_extracted_column()) {
1049
            const auto& name = column->name();
1050
            if (name.find("." + DOC_VALUE_COLUMN_PATH + ".") != std::string::npos ||
1051
                name.find("." + SPARSE_COLUMN_PATH + ".") != std::string::npos ||
1052
                name.ends_with("." + SPARSE_COLUMN_PATH)) {
1053
                continue;
1054
            }
1055
            return Status::InternalError("Unexpected extracted column {} in output rowset",
1056
                                         column->name());
1057
        }
1058
    }
1059
#endif
1060
    // only check path stats for dup_keys since the rows may be merged in other models
1061
5
    if (tablet->keys_type() != KeysType::DUP_KEYS) {
1062
2
        return Status::OK();
1063
2
    }
1064
    // if there is a delete predicate in the input rowsets, we skip the path stats check
1065
15
    for (auto& rowset : intputs) {
1066
15
        if (rowset->rowset_meta()->has_delete_predicate()) {
1067
0
            return Status::OK();
1068
0
        }
1069
15
    }
1070
15
    for (const auto& column : output->tablet_schema()->columns()) {
1071
15
        if (column->is_variant_type() && !should_check_variant_path_stats(*column)) {
1072
0
            return Status::OK();
1073
0
        }
1074
15
    }
1075
3
    std::unordered_map<int32_t, PathToNoneNullValues> original_uid_to_path_stats;
1076
15
    for (const auto& rs : intputs) {
1077
15
        RETURN_IF_ERROR(aggregate_path_to_stats(rs, &original_uid_to_path_stats));
1078
15
    }
1079
3
    std::unordered_map<int32_t, PathToNoneNullValues> output_uid_to_path_stats;
1080
3
    RETURN_IF_ERROR(aggregate_path_to_stats(output, &output_uid_to_path_stats));
1081
5
    for (const auto& [uid, stats] : output_uid_to_path_stats) {
1082
5
        if (output->tablet_schema()->column_by_uid(uid).is_variant_type() &&
1083
5
            output->tablet_schema()->column_by_uid(uid).variant_enable_doc_mode()) {
1084
0
            continue;
1085
0
        }
1086
5
        if (original_uid_to_path_stats.find(uid) == original_uid_to_path_stats.end()) {
1087
0
            return Status::InternalError("Path stats not found for uid {}, tablet_id {}", uid,
1088
0
                                         tablet->tablet_id());
1089
0
        }
1090
1091
        // In input rowsets, some rowsets may have statistics values exceeding the maximum limit,
1092
        // which leads to inaccurate statistics
1093
5
        if (stats.size() > output->tablet_schema()
1094
5
                                   ->column_by_uid(uid)
1095
5
                                   .variant_max_sparse_column_statistics_size()) {
1096
            // When there is only one segment, we can ensure that the size of each path in output stats is accurate
1097
0
            if (output->num_segments() == 1) {
1098
0
                for (const auto& [path, size] : stats) {
1099
0
                    if (original_uid_to_path_stats.at(uid).find(path) ==
1100
0
                        original_uid_to_path_stats.at(uid).end()) {
1101
0
                        continue;
1102
0
                    }
1103
0
                    if (original_uid_to_path_stats.at(uid).at(path) > size) {
1104
0
                        return Status::InternalError(
1105
0
                                "Path stats not smaller for uid {} with path `{}`, input size {}, "
1106
0
                                "output "
1107
0
                                "size {}, "
1108
0
                                "tablet_id {}",
1109
0
                                uid, path, original_uid_to_path_stats.at(uid).at(path), size,
1110
0
                                tablet->tablet_id());
1111
0
                    }
1112
0
                }
1113
0
            }
1114
0
        }
1115
        // in this case, input stats is accurate, so we check the stats size and stats value
1116
5
        else {
1117
41
            for (const auto& [path, size] : stats) {
1118
41
                if (original_uid_to_path_stats.at(uid).find(path) ==
1119
41
                    original_uid_to_path_stats.at(uid).end()) {
1120
0
                    return Status::InternalError(
1121
0
                            "Path stats not found for uid {}, path {}, tablet_id {}", uid, path,
1122
0
                            tablet->tablet_id());
1123
0
                }
1124
41
                if (original_uid_to_path_stats.at(uid).at(path) != size) {
1125
1
                    return Status::InternalError(
1126
1
                            "Path stats not match for uid {} with path `{}`, input size {}, output "
1127
1
                            "size {}, "
1128
1
                            "tablet_id {}",
1129
1
                            uid, path, original_uid_to_path_stats.at(uid).at(path), size,
1130
1
                            tablet->tablet_id());
1131
1
                }
1132
41
            }
1133
5
        }
1134
5
    }
1135
1136
2
    return Status::OK();
1137
3
}
1138
1139
Status VariantCompactionUtil::get_compaction_typed_columns(
1140
        const TabletSchemaSPtr& target, const std::unordered_set<std::string>& typed_paths,
1141
        const TabletColumnPtr parent_column, TabletSchemaSPtr& output_schema,
1142
9
        TabletSchema::PathsSetInfo& paths_set_info) {
1143
9
    if (parent_column->variant_enable_typed_paths_to_sparse()) {
1144
0
        return Status::OK();
1145
0
    }
1146
9
    for (const auto& path : typed_paths) {
1147
4
        TabletSchema::SubColumnInfo sub_column_info;
1148
4
        if (generate_sub_column_info(*target, parent_column->unique_id(), path, &sub_column_info)) {
1149
3
            inherit_column_attributes(*parent_column, sub_column_info.column);
1150
3
            output_schema->append_column(sub_column_info.column);
1151
3
            paths_set_info.typed_path_set.insert({path, std::move(sub_column_info)});
1152
3
            VLOG_DEBUG << "append typed column " << path;
1153
3
        } else {
1154
1
            return Status::InternalError("Failed to generate sub column info for path {}", path);
1155
1
        }
1156
4
    }
1157
8
    return Status::OK();
1158
9
}
1159
1160
Status VariantCompactionUtil::get_compaction_nested_columns(
1161
        const std::unordered_set<PathInData, PathInData::Hash>& nested_paths,
1162
        const PathToDataTypes& path_to_data_types, const TabletColumnPtr parent_column,
1163
8
        TabletSchemaSPtr& output_schema, TabletSchema::PathsSetInfo& paths_set_info) {
1164
8
    const auto& parent_indexes = output_schema->inverted_indexs(parent_column->unique_id());
1165
8
    for (const auto& path : nested_paths) {
1166
3
        const auto& find_data_types = path_to_data_types.find(path);
1167
3
        if (find_data_types == path_to_data_types.end() || find_data_types->second.empty()) {
1168
1
            return Status::InternalError("Nested path {} has no data type", path.get_path());
1169
1
        }
1170
2
        DataTypePtr data_type;
1171
2
        get_least_supertype_jsonb(find_data_types->second, &data_type);
1172
1173
2
        const std::string& column_name = parent_column->name_lower_case() + "." + path.get_path();
1174
2
        PathInDataBuilder full_path_builder;
1175
2
        auto full_path = full_path_builder.append(parent_column->name_lower_case(), false)
1176
2
                                 .append(path.get_parts(), false)
1177
2
                                 .build();
1178
2
        TabletColumn nested_column =
1179
2
                get_column_by_type(data_type, column_name,
1180
2
                                   ExtraInfo {.unique_id = -1,
1181
2
                                              .parent_unique_id = parent_column->unique_id(),
1182
2
                                              .path_info = full_path});
1183
2
        inherit_column_attributes(*parent_column, nested_column);
1184
2
        TabletIndexes sub_column_indexes;
1185
2
        inherit_index(parent_indexes, sub_column_indexes, nested_column);
1186
2
        paths_set_info.subcolumn_indexes.emplace(path.get_path(), std::move(sub_column_indexes));
1187
2
        output_schema->append_column(nested_column);
1188
2
        VLOG_DEBUG << "append nested column " << path.get_path();
1189
2
    }
1190
7
    return Status::OK();
1191
8
}
1192
1193
void VariantCompactionUtil::get_compaction_subcolumns_from_subpaths(
1194
        TabletSchema::PathsSetInfo& paths_set_info, const TabletColumnPtr parent_column,
1195
        const TabletSchemaSPtr& target, const PathToDataTypes& path_to_data_types,
1196
13
        const std::unordered_set<std::string>& sparse_paths, TabletSchemaSPtr& output_schema) {
1197
13
    auto& path_set = paths_set_info.sub_path_set;
1198
13
    std::vector<StringRef> sorted_subpaths(path_set.begin(), path_set.end());
1199
13
    std::sort(sorted_subpaths.begin(), sorted_subpaths.end());
1200
13
    const auto& parent_indexes = target->inverted_indexs(parent_column->unique_id());
1201
    // append subcolumns
1202
38
    for (const auto& subpath : sorted_subpaths) {
1203
38
        auto column_name = parent_column->name_lower_case() + "." + subpath.to_string();
1204
38
        auto column_path = PathInData(column_name);
1205
1206
38
        const auto& find_data_types = path_to_data_types.find(PathInData(subpath));
1207
1208
        // some cases: the subcolumn type is variant
1209
        // 1. this path has no data type in segments
1210
        // 2. this path is in sparse paths
1211
        // 3. the sparse paths are too much
1212
38
        TabletSchema::SubColumnInfo sub_column_info;
1213
38
        if (parent_column->variant_enable_typed_paths_to_sparse() &&
1214
38
            generate_sub_column_info(*target, parent_column->unique_id(), std::string(subpath),
1215
16
                                     &sub_column_info)) {
1216
8
            inherit_column_attributes(*parent_column, sub_column_info.column);
1217
8
            output_schema->append_column(sub_column_info.column);
1218
8
            paths_set_info.subcolumn_indexes.emplace(subpath, std::move(sub_column_info.indexes));
1219
8
            VLOG_DEBUG << "append typed column " << subpath;
1220
30
        } else if (find_data_types == path_to_data_types.end() || find_data_types->second.empty() ||
1221
30
                   sparse_paths.find(std::string(subpath)) != sparse_paths.end() ||
1222
30
                   sparse_paths.size() >=
1223
22
                           parent_column->variant_max_sparse_column_statistics_size()) {
1224
12
            TabletColumn subcolumn;
1225
12
            subcolumn.set_name(column_name);
1226
12
            subcolumn.set_type(FieldType::OLAP_FIELD_TYPE_VARIANT);
1227
12
            subcolumn.set_parent_unique_id(parent_column->unique_id());
1228
12
            subcolumn.set_path_info(column_path);
1229
12
            subcolumn.set_aggregation_method(parent_column->aggregation());
1230
12
            subcolumn.set_variant_max_subcolumns_count(
1231
12
                    parent_column->variant_max_subcolumns_count());
1232
12
            subcolumn.set_variant_enable_doc_mode(parent_column->variant_enable_doc_mode());
1233
12
            subcolumn.set_is_nullable(true);
1234
12
            output_schema->append_column(subcolumn);
1235
12
            VLOG_DEBUG << "append sub column " << subpath << " data type "
1236
0
                       << "VARIANT";
1237
12
        }
1238
        // normal case: the subcolumn type can be calculated from the data types in segments
1239
18
        else {
1240
18
            DataTypePtr data_type;
1241
18
            get_least_supertype_jsonb(find_data_types->second, &data_type);
1242
18
            TabletColumn sub_column =
1243
18
                    get_column_by_type(data_type, column_name,
1244
18
                                       ExtraInfo {.unique_id = -1,
1245
18
                                                  .parent_unique_id = parent_column->unique_id(),
1246
18
                                                  .path_info = column_path});
1247
18
            inherit_column_attributes(*parent_column, sub_column);
1248
18
            TabletIndexes sub_column_indexes;
1249
18
            inherit_index(parent_indexes, sub_column_indexes, sub_column);
1250
18
            paths_set_info.subcolumn_indexes.emplace(subpath, std::move(sub_column_indexes));
1251
18
            output_schema->append_column(sub_column);
1252
18
            VLOG_DEBUG << "append sub column " << subpath << " data type " << data_type->get_name();
1253
18
        }
1254
38
    }
1255
13
}
1256
1257
void VariantCompactionUtil::get_compaction_subcolumns_from_data_types(
1258
        TabletSchema::PathsSetInfo& paths_set_info, const TabletColumnPtr parent_column,
1259
        const TabletSchemaSPtr& target, const PathToDataTypes& path_to_data_types,
1260
3
        TabletSchemaSPtr& output_schema) {
1261
3
    const auto& parent_indexes = target->inverted_indexs(parent_column->unique_id());
1262
4
    for (const auto& [path, data_types] : path_to_data_types) {
1263
        // Typed paths are materialized by get_compaction_typed_columns(); this helper only
1264
        // materializes regular subcolumns inferred from rowset data types.
1265
4
        if (data_types.empty() || path.empty() || path.get_is_typed() || path.has_nested_part()) {
1266
1
            continue;
1267
1
        }
1268
3
        DataTypePtr data_type;
1269
3
        get_least_supertype_jsonb(data_types, &data_type);
1270
3
        auto column_name = parent_column->name_lower_case() + "." + path.get_path();
1271
3
        auto column_path = PathInData(column_name);
1272
3
        TabletColumn sub_column =
1273
3
                get_column_by_type(data_type, column_name,
1274
3
                                   ExtraInfo {.unique_id = -1,
1275
3
                                              .parent_unique_id = parent_column->unique_id(),
1276
3
                                              .path_info = column_path});
1277
3
        inherit_column_attributes(*parent_column, sub_column);
1278
3
        TabletIndexes sub_column_indexes;
1279
3
        inherit_index(parent_indexes, sub_column_indexes, sub_column);
1280
3
        paths_set_info.sub_path_set.emplace(path.get_path());
1281
3
        paths_set_info.subcolumn_indexes.emplace(path.get_path(), std::move(sub_column_indexes));
1282
3
        output_schema->append_column(sub_column);
1283
3
        VLOG_DEBUG << "append sub column " << path.get_path() << " data type "
1284
0
                   << data_type->get_name();
1285
3
    }
1286
3
}
1287
1288
// Build the temporary schema for compaction.
1289
// NestedGroup roots are special: the root VARIANT column owns the NG tree and the streaming NG
1290
// writer handles NG children, while regular non-NG paths beside the arrays are materialized as
1291
// ordinary extracted subcolumns. NG typed paths still use get_compaction_typed_columns(), keeping
1292
// typed-column rules out of the NG-specific regular-path filtering.
1293
Status VariantCompactionUtil::get_extended_compaction_schema(
1294
41
        const std::vector<RowsetSharedPtr>& rowsets, TabletSchemaSPtr& target) {
1295
41
    std::unordered_map<int32_t, VariantExtendedInfo> uid_to_variant_extended_info;
1296
41
    const bool needs_variant_extended_info =
1297
821
            std::ranges::any_of(target->columns(), [](const TabletColumnPtr& column) {
1298
821
                return column->is_variant_type() && (should_check_variant_path_stats(*column) ||
1299
5
                                                     column->variant_enable_nested_group());
1300
821
            });
1301
41
    if (needs_variant_extended_info) {
1302
        // collect path stats from all rowsets and segments
1303
10
        for (const auto& rs : rowsets) {
1304
10
            RETURN_IF_ERROR(aggregate_variant_extended_info(rs, &uid_to_variant_extended_info));
1305
10
        }
1306
5
    }
1307
1308
    // build the output schema
1309
41
    TabletSchemaSPtr output_schema = std::make_shared<TabletSchema>();
1310
41
    output_schema->shawdow_copy_without_columns(*target);
1311
41
    std::unordered_map<int32_t, TabletSchema::PathsSetInfo> uid_to_paths_set_info;
1312
41
    const auto ng_root_uids =
1313
41
            collect_nested_group_compaction_root_uids(target, uid_to_variant_extended_info);
1314
828
    for (const TabletColumnPtr& column : target->columns()) {
1315
828
        if (!column->is_extracted_column()) {
1316
827
            output_schema->append_column(*column);
1317
827
        }
1318
828
        if (!column->is_variant_type()) {
1319
821
            continue;
1320
821
        }
1321
7
        VLOG_DEBUG << "column " << column->name() << " unique id " << column->unique_id();
1322
1323
7
        const auto info_it = uid_to_variant_extended_info.find(column->unique_id());
1324
7
        const VariantExtendedInfo empty_extended_info;
1325
7
        const VariantExtendedInfo& extended_info = info_it == uid_to_variant_extended_info.end()
1326
7
                                                           ? empty_extended_info
1327
7
                                                           : info_it->second;
1328
7
        auto& paths_set_info = uid_to_paths_set_info[column->unique_id()];
1329
7
        const bool use_nested_group_compaction_schema = ng_root_uids.contains(column->unique_id());
1330
1331
7
        if (use_nested_group_compaction_schema) {
1332
            // 1. append typed columns. Keep this shared with the non-NG typed helper; only the
1333
            // regular-path selection below is NG-specific.
1334
1
            RETURN_IF_ERROR(get_compaction_typed_columns(target, extended_info.typed_paths, column,
1335
1
                                                         output_schema, paths_set_info));
1336
1337
            // NG roots do not record path-count stats for ordinary Variant paths, so their regular
1338
            // non-NG subcolumns use the same data-types materialization helper as the
1339
            // all-materialized non-NG branch below.
1340
1
            auto regular_path_to_data_types =
1341
1
                    collect_regular_types_outside_nested_group(extended_info);
1342
1
            get_compaction_subcolumns_from_data_types(paths_set_info, column, target,
1343
1
                                                      regular_path_to_data_types, output_schema);
1344
1
            LOG(INFO) << "Variant column uid=" << column->unique_id()
1345
1
                      << " keeps nested-group root and materializes regular non-NG subcolumns in "
1346
1
                         "compaction schema";
1347
1
            continue;
1348
1
        }
1349
1350
6
        if (column->variant_enable_doc_mode()) {
1351
0
            const int bucket_num = std::max(1, column->variant_doc_hash_shard_count());
1352
0
            for (int b = 0; b < bucket_num; ++b) {
1353
0
                TabletColumn doc_value_bucket_column = create_doc_value_column(*column, b);
1354
0
                doc_value_bucket_column.set_type(FieldType::OLAP_FIELD_TYPE_VARIANT);
1355
0
                doc_value_bucket_column.set_is_nullable(false);
1356
0
                doc_value_bucket_column.set_variant_enable_doc_mode(true);
1357
0
                output_schema->append_column(doc_value_bucket_column);
1358
0
            }
1359
0
            continue;
1360
0
        }
1361
1362
        // 1. append typed columns
1363
6
        RETURN_IF_ERROR(get_compaction_typed_columns(target, extended_info.typed_paths, column,
1364
6
                                                     output_schema, paths_set_info));
1365
1366
        // 2. append nested columns
1367
6
        RETURN_IF_ERROR(get_compaction_nested_columns(extended_info.nested_paths,
1368
6
                                                      extended_info.path_to_data_types, column,
1369
6
                                                      output_schema, paths_set_info));
1370
1371
        // 3. get the subpaths
1372
6
        get_subpaths(column->variant_max_subcolumns_count(), extended_info.path_to_none_null_values,
1373
6
                     paths_set_info);
1374
1375
        // 4. append subcolumns
1376
6
        if (column->variant_max_subcolumns_count() > 0 || !column->get_sub_columns().empty()) {
1377
5
            get_compaction_subcolumns_from_subpaths(paths_set_info, column, target,
1378
5
                                                    extended_info.path_to_data_types,
1379
5
                                                    extended_info.sparse_paths, output_schema);
1380
5
        }
1381
        // variant_max_subcolumns_count == 0 and no typed paths materialized
1382
        // it means that all subcolumns are materialized, may be from old data
1383
1
        else {
1384
1
            get_compaction_subcolumns_from_data_types(paths_set_info, column, target,
1385
1
                                                      extended_info.path_to_data_types,
1386
1
                                                      output_schema);
1387
1
        }
1388
1389
        // append sparse column(s)
1390
        // If variant uses bucketized sparse columns, append one sparse bucket column per bucket.
1391
        // Otherwise, append the single sparse column.
1392
6
        int bucket_num = std::max(1, column->variant_sparse_hash_shard_count());
1393
6
        if (bucket_num > 1) {
1394
0
            for (int b = 0; b < bucket_num; ++b) {
1395
0
                TabletColumn sparse_bucket_column = create_sparse_shard_column(*column, b);
1396
0
                output_schema->append_column(sparse_bucket_column);
1397
0
            }
1398
6
        } else {
1399
6
            TabletColumn sparse_column = create_sparse_column(*column);
1400
6
            output_schema->append_column(sparse_column);
1401
6
        }
1402
6
    }
1403
1404
41
    target = output_schema;
1405
    // used to merge & filter path to sparse column during reading in compaction
1406
41
    target->set_path_set_info(std::move(uid_to_paths_set_info));
1407
41
    VLOG_DEBUG << "dump schema " << target->dump_full_schema();
1408
41
    return Status::OK();
1409
41
}
1410
1411
// Calculate statistics about variant data paths from the encoded sparse column
1412
void VariantCompactionUtil::calculate_variant_stats(const IColumn& encoded_sparse_column,
1413
                                                    segment_v2::VariantStatisticsPB* stats,
1414
                                                    size_t max_sparse_column_statistics_size,
1415
3
                                                    size_t row_pos, size_t num_rows) {
1416
    // Cast input column to ColumnMap type since sparse column is stored as a map
1417
3
    const auto& map_column = assert_cast<const ColumnMap&>(encoded_sparse_column);
1418
1419
    // Get the keys column which contains the paths as strings
1420
3
    const auto& sparse_data_paths =
1421
3
            assert_cast<const ColumnString*>(map_column.get_keys_ptr().get());
1422
3
    const auto& serialized_sparse_column_offsets = map_column.get_offsets();
1423
3
    auto& count_map = *stats->mutable_sparse_column_non_null_size();
1424
    // Iterate through all paths in the sparse column
1425
11
    for (size_t i = row_pos; i != row_pos + num_rows; ++i) {
1426
8
        size_t offset = serialized_sparse_column_offsets[i - 1];
1427
8
        size_t end = serialized_sparse_column_offsets[i];
1428
10
        for (size_t j = offset; j != end; ++j) {
1429
2
            auto path = sparse_data_paths->get_data_at(j);
1430
1431
2
            const auto& sparse_path = path.to_string();
1432
            // If path already exists in statistics, increment its count
1433
2
            if (auto it = count_map.find(sparse_path); it != count_map.end()) {
1434
0
                ++it->second;
1435
0
            }
1436
            // If path doesn't exist and we haven't hit the max statistics size limit,
1437
            // add it with count 1
1438
2
            else if (count_map.size() < max_sparse_column_statistics_size) {
1439
2
                count_map.emplace(sparse_path, 1);
1440
2
            }
1441
2
        }
1442
8
    }
1443
1444
3
    if (stats->sparse_column_non_null_size().size() > max_sparse_column_statistics_size) {
1445
0
        throw doris::Exception(
1446
0
                ErrorCode::INTERNAL_ERROR,
1447
0
                "Sparse column non null size: {} is greater than max statistics size: {}",
1448
0
                stats->sparse_column_non_null_size().size(), max_sparse_column_statistics_size);
1449
0
    }
1450
3
}
1451
1452
/// Calculates number of dimensions in array field.
1453
/// Returns 0 for scalar fields.
1454
class FieldVisitorToNumberOfDimensions : public StaticVisitor<size_t> {
1455
public:
1456
    FieldVisitorToNumberOfDimensions() = default;
1457
    template <PrimitiveType T>
1458
2.24M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
2.24M
        if constexpr (T == TYPE_ARRAY) {
1460
127k
            const size_t size = x.size();
1461
127k
            size_t dimensions = 0;
1462
873k
            for (size_t i = 0; i < size; ++i) {
1463
745k
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
745k
                dimensions = std::max(dimensions, element_dimensions);
1465
745k
            }
1466
127k
            return 1 + dimensions;
1467
2.11M
        } else {
1468
2.11M
            return 0;
1469
2.11M
        }
1470
2.24M
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE1EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1458
24.0k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
        if constexpr (T == TYPE_ARRAY) {
1460
            const size_t size = x.size();
1461
            size_t dimensions = 0;
1462
            for (size_t i = 0; i < size; ++i) {
1463
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
                dimensions = std::max(dimensions, element_dimensions);
1465
            }
1466
            return 1 + dimensions;
1467
24.0k
        } else {
1468
24.0k
            return 0;
1469
24.0k
        }
1470
24.0k
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE26EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE42EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE7EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1458
40.9k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
        if constexpr (T == TYPE_ARRAY) {
1460
            const size_t size = x.size();
1461
            size_t dimensions = 0;
1462
            for (size_t i = 0; i < size; ++i) {
1463
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
                dimensions = std::max(dimensions, element_dimensions);
1465
            }
1466
            return 1 + dimensions;
1467
40.9k
        } else {
1468
40.9k
            return 0;
1469
40.9k
        }
1470
40.9k
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE12EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE11EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE25EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE2EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1458
69.6k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
        if constexpr (T == TYPE_ARRAY) {
1460
            const size_t size = x.size();
1461
            size_t dimensions = 0;
1462
            for (size_t i = 0; i < size; ++i) {
1463
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
                dimensions = std::max(dimensions, element_dimensions);
1465
            }
1466
            return 1 + dimensions;
1467
69.6k
        } else {
1468
69.6k
            return 0;
1469
69.6k
        }
1470
69.6k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE3EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1458
6
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
        if constexpr (T == TYPE_ARRAY) {
1460
            const size_t size = x.size();
1461
            size_t dimensions = 0;
1462
            for (size_t i = 0; i < size; ++i) {
1463
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
                dimensions = std::max(dimensions, element_dimensions);
1465
            }
1466
            return 1 + dimensions;
1467
6
        } else {
1468
6
            return 0;
1469
6
        }
1470
6
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE4EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1458
7
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
        if constexpr (T == TYPE_ARRAY) {
1460
            const size_t size = x.size();
1461
            size_t dimensions = 0;
1462
            for (size_t i = 0; i < size; ++i) {
1463
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
                dimensions = std::max(dimensions, element_dimensions);
1465
            }
1466
            return 1 + dimensions;
1467
7
        } else {
1468
7
            return 0;
1469
7
        }
1470
7
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE5EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1458
951
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
        if constexpr (T == TYPE_ARRAY) {
1460
            const size_t size = x.size();
1461
            size_t dimensions = 0;
1462
            for (size_t i = 0; i < size; ++i) {
1463
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
                dimensions = std::max(dimensions, element_dimensions);
1465
            }
1466
            return 1 + dimensions;
1467
951
        } else {
1468
951
            return 0;
1469
951
        }
1470
951
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE6EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1458
851k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
        if constexpr (T == TYPE_ARRAY) {
1460
            const size_t size = x.size();
1461
            size_t dimensions = 0;
1462
            for (size_t i = 0; i < size; ++i) {
1463
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
                dimensions = std::max(dimensions, element_dimensions);
1465
            }
1466
            return 1 + dimensions;
1467
851k
        } else {
1468
851k
            return 0;
1469
851k
        }
1470
851k
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE38EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE39EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE8EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1458
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
        if constexpr (T == TYPE_ARRAY) {
1460
            const size_t size = x.size();
1461
            size_t dimensions = 0;
1462
            for (size_t i = 0; i < size; ++i) {
1463
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
                dimensions = std::max(dimensions, element_dimensions);
1465
            }
1466
            return 1 + dimensions;
1467
1
        } else {
1468
1
            return 0;
1469
1
        }
1470
1
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE27EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE9EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1458
164k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
        if constexpr (T == TYPE_ARRAY) {
1460
            const size_t size = x.size();
1461
            size_t dimensions = 0;
1462
            for (size_t i = 0; i < size; ++i) {
1463
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
                dimensions = std::max(dimensions, element_dimensions);
1465
            }
1466
            return 1 + dimensions;
1467
164k
        } else {
1468
164k
            return 0;
1469
164k
        }
1470
164k
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE36EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE37EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE23EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1458
967k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
        if constexpr (T == TYPE_ARRAY) {
1460
            const size_t size = x.size();
1461
            size_t dimensions = 0;
1462
            for (size_t i = 0; i < size; ++i) {
1463
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
                dimensions = std::max(dimensions, element_dimensions);
1465
            }
1466
            return 1 + dimensions;
1467
967k
        } else {
1468
967k
            return 0;
1469
967k
        }
1470
967k
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE15EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE10EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE41EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE17EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1458
127k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
127k
        if constexpr (T == TYPE_ARRAY) {
1460
127k
            const size_t size = x.size();
1461
127k
            size_t dimensions = 0;
1462
873k
            for (size_t i = 0; i < size; ++i) {
1463
745k
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
745k
                dimensions = std::max(dimensions, element_dimensions);
1465
745k
            }
1466
127k
            return 1 + dimensions;
1467
        } else {
1468
            return 0;
1469
        }
1470
127k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE16EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1458
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
        if constexpr (T == TYPE_ARRAY) {
1460
            const size_t size = x.size();
1461
            size_t dimensions = 0;
1462
            for (size_t i = 0; i < size; ++i) {
1463
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
                dimensions = std::max(dimensions, element_dimensions);
1465
            }
1466
            return 1 + dimensions;
1467
1
        } else {
1468
1
            return 0;
1469
1
        }
1470
1
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE18EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE32EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1458
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
        if constexpr (T == TYPE_ARRAY) {
1460
            const size_t size = x.size();
1461
            size_t dimensions = 0;
1462
            for (size_t i = 0; i < size; ++i) {
1463
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
                dimensions = std::max(dimensions, element_dimensions);
1465
            }
1466
            return 1 + dimensions;
1467
1
        } else {
1468
1
            return 0;
1469
1
        }
1470
1
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE28EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE29EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE20EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE30EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE35EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE22EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE19EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE24EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE31EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1458
27
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1459
        if constexpr (T == TYPE_ARRAY) {
1460
            const size_t size = x.size();
1461
            size_t dimensions = 0;
1462
            for (size_t i = 0; i < size; ++i) {
1463
                size_t element_dimensions = apply_visitor(*this, x[i]);
1464
                dimensions = std::max(dimensions, element_dimensions);
1465
            }
1466
            return 1 + dimensions;
1467
27
        } else {
1468
27
            return 0;
1469
27
        }
1470
27
    }
1471
};
1472
1473
// Visitor that allows to get type of scalar field
1474
// but exclude fields contain complex field.This is a faster version
1475
// for FieldVisitorToScalarType which does not support complex field.
1476
class SimpleFieldVisitorToScalarType : public StaticVisitor<size_t> {
1477
public:
1478
    template <PrimitiveType T>
1479
1.42M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1480
1.42M
        if constexpr (T == TYPE_ARRAY) {
1481
0
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1482
12.3k
        } else if constexpr (T == TYPE_NULL) {
1483
12.3k
            have_nulls = true;
1484
12.3k
            return 1;
1485
1.41M
        } else {
1486
1.41M
            type = T;
1487
1.41M
            return 1;
1488
1.41M
        }
1489
1.42M
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE1EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1479
12.3k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1480
        if constexpr (T == TYPE_ARRAY) {
1481
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1482
12.3k
        } else if constexpr (T == TYPE_NULL) {
1483
12.3k
            have_nulls = true;
1484
12.3k
            return 1;
1485
        } else {
1486
            type = T;
1487
            return 1;
1488
        }
1489
12.3k
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE26EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE42EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE7EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1479
12.3k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1480
        if constexpr (T == TYPE_ARRAY) {
1481
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1482
        } else if constexpr (T == TYPE_NULL) {
1483
            have_nulls = true;
1484
            return 1;
1485
12.3k
        } else {
1486
12.3k
            type = T;
1487
12.3k
            return 1;
1488
12.3k
        }
1489
12.3k
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE12EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE11EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE25EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE2EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1479
12.4k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1480
        if constexpr (T == TYPE_ARRAY) {
1481
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1482
        } else if constexpr (T == TYPE_NULL) {
1483
            have_nulls = true;
1484
            return 1;
1485
12.4k
        } else {
1486
12.4k
            type = T;
1487
12.4k
            return 1;
1488
12.4k
        }
1489
12.4k
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE3EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1479
2
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1480
        if constexpr (T == TYPE_ARRAY) {
1481
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1482
        } else if constexpr (T == TYPE_NULL) {
1483
            have_nulls = true;
1484
            return 1;
1485
2
        } else {
1486
2
            type = T;
1487
2
            return 1;
1488
2
        }
1489
2
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE4EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1479
7
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1480
        if constexpr (T == TYPE_ARRAY) {
1481
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1482
        } else if constexpr (T == TYPE_NULL) {
1483
            have_nulls = true;
1484
            return 1;
1485
7
        } else {
1486
7
            type = T;
1487
7
            return 1;
1488
7
        }
1489
7
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE5EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1479
570
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1480
        if constexpr (T == TYPE_ARRAY) {
1481
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1482
        } else if constexpr (T == TYPE_NULL) {
1483
            have_nulls = true;
1484
            return 1;
1485
570
        } else {
1486
570
            type = T;
1487
570
            return 1;
1488
570
        }
1489
570
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE6EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1479
703k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1480
        if constexpr (T == TYPE_ARRAY) {
1481
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1482
        } else if constexpr (T == TYPE_NULL) {
1483
            have_nulls = true;
1484
            return 1;
1485
703k
        } else {
1486
703k
            type = T;
1487
703k
            return 1;
1488
703k
        }
1489
703k
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE38EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE39EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE8EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1479
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1480
        if constexpr (T == TYPE_ARRAY) {
1481
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1482
        } else if constexpr (T == TYPE_NULL) {
1483
            have_nulls = true;
1484
            return 1;
1485
1
        } else {
1486
1
            type = T;
1487
1
            return 1;
1488
1
        }
1489
1
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE27EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE9EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1479
12.6k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1480
        if constexpr (T == TYPE_ARRAY) {
1481
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1482
        } else if constexpr (T == TYPE_NULL) {
1483
            have_nulls = true;
1484
            return 1;
1485
12.6k
        } else {
1486
12.6k
            type = T;
1487
12.6k
            return 1;
1488
12.6k
        }
1489
12.6k
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE36EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE37EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE23EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1479
670k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1480
        if constexpr (T == TYPE_ARRAY) {
1481
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1482
        } else if constexpr (T == TYPE_NULL) {
1483
            have_nulls = true;
1484
            return 1;
1485
670k
        } else {
1486
670k
            type = T;
1487
670k
            return 1;
1488
670k
        }
1489
670k
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE15EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE10EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE41EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE17EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE16EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE18EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE32EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE28EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE29EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE20EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE30EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE35EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE22EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE19EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE24EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE31EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1479
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1480
        if constexpr (T == TYPE_ARRAY) {
1481
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1482
        } else if constexpr (T == TYPE_NULL) {
1483
            have_nulls = true;
1484
            return 1;
1485
1
        } else {
1486
1
            type = T;
1487
1
            return 1;
1488
1
        }
1489
1
    }
1490
1.42M
    void get_scalar_type(PrimitiveType* data_type) const { *data_type = type; }
1491
1.42M
    bool contain_nulls() const { return have_nulls; }
1492
1493
1.42M
    bool need_convert_field() const { return false; }
1494
1495
private:
1496
    PrimitiveType type = PrimitiveType::INVALID_TYPE;
1497
    bool have_nulls = false;
1498
};
1499
1500
/// Visitor that allows to get type of scalar field
1501
/// or least common type of scalars in array.
1502
/// More optimized version of FieldToDataType.
1503
class FieldVisitorToScalarType : public StaticVisitor<size_t> {
1504
public:
1505
    template <PrimitiveType T>
1506
823k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1507
823k
        if constexpr (T == TYPE_ARRAY) {
1508
127k
            size_t size = x.size();
1509
873k
            for (size_t i = 0; i < size; ++i) {
1510
745k
                apply_visitor(*this, x[i]);
1511
745k
            }
1512
127k
            return 0;
1513
127k
        } else if constexpr (T == TYPE_NULL) {
1514
11.6k
            have_nulls = true;
1515
11.6k
            return 0;
1516
683k
        } else {
1517
683k
            field_types.insert(T);
1518
683k
            type_indexes.insert(T);
1519
683k
            return 0;
1520
683k
        }
1521
823k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE1EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1506
11.6k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1507
        if constexpr (T == TYPE_ARRAY) {
1508
            size_t size = x.size();
1509
            for (size_t i = 0; i < size; ++i) {
1510
                apply_visitor(*this, x[i]);
1511
            }
1512
            return 0;
1513
11.6k
        } else if constexpr (T == TYPE_NULL) {
1514
11.6k
            have_nulls = true;
1515
11.6k
            return 0;
1516
        } else {
1517
            field_types.insert(T);
1518
            type_indexes.insert(T);
1519
            return 0;
1520
        }
1521
11.6k
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE26EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE42EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE7EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1506
28.6k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1507
        if constexpr (T == TYPE_ARRAY) {
1508
            size_t size = x.size();
1509
            for (size_t i = 0; i < size; ++i) {
1510
                apply_visitor(*this, x[i]);
1511
            }
1512
            return 0;
1513
        } else if constexpr (T == TYPE_NULL) {
1514
            have_nulls = true;
1515
            return 0;
1516
28.6k
        } else {
1517
28.6k
            field_types.insert(T);
1518
28.6k
            type_indexes.insert(T);
1519
28.6k
            return 0;
1520
28.6k
        }
1521
28.6k
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE12EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE11EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE25EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE2EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1506
57.2k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1507
        if constexpr (T == TYPE_ARRAY) {
1508
            size_t size = x.size();
1509
            for (size_t i = 0; i < size; ++i) {
1510
                apply_visitor(*this, x[i]);
1511
            }
1512
            return 0;
1513
        } else if constexpr (T == TYPE_NULL) {
1514
            have_nulls = true;
1515
            return 0;
1516
57.2k
        } else {
1517
57.2k
            field_types.insert(T);
1518
57.2k
            type_indexes.insert(T);
1519
57.2k
            return 0;
1520
57.2k
        }
1521
57.2k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE3EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1506
4
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1507
        if constexpr (T == TYPE_ARRAY) {
1508
            size_t size = x.size();
1509
            for (size_t i = 0; i < size; ++i) {
1510
                apply_visitor(*this, x[i]);
1511
            }
1512
            return 0;
1513
        } else if constexpr (T == TYPE_NULL) {
1514
            have_nulls = true;
1515
            return 0;
1516
4
        } else {
1517
4
            field_types.insert(T);
1518
4
            type_indexes.insert(T);
1519
4
            return 0;
1520
4
        }
1521
4
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE4EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE5EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1506
381
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1507
        if constexpr (T == TYPE_ARRAY) {
1508
            size_t size = x.size();
1509
            for (size_t i = 0; i < size; ++i) {
1510
                apply_visitor(*this, x[i]);
1511
            }
1512
            return 0;
1513
        } else if constexpr (T == TYPE_NULL) {
1514
            have_nulls = true;
1515
            return 0;
1516
381
        } else {
1517
381
            field_types.insert(T);
1518
381
            type_indexes.insert(T);
1519
381
            return 0;
1520
381
        }
1521
381
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE6EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1506
147k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1507
        if constexpr (T == TYPE_ARRAY) {
1508
            size_t size = x.size();
1509
            for (size_t i = 0; i < size; ++i) {
1510
                apply_visitor(*this, x[i]);
1511
            }
1512
            return 0;
1513
        } else if constexpr (T == TYPE_NULL) {
1514
            have_nulls = true;
1515
            return 0;
1516
147k
        } else {
1517
147k
            field_types.insert(T);
1518
147k
            type_indexes.insert(T);
1519
147k
            return 0;
1520
147k
        }
1521
147k
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE38EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE39EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE8EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE27EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE9EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1506
151k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1507
        if constexpr (T == TYPE_ARRAY) {
1508
            size_t size = x.size();
1509
            for (size_t i = 0; i < size; ++i) {
1510
                apply_visitor(*this, x[i]);
1511
            }
1512
            return 0;
1513
        } else if constexpr (T == TYPE_NULL) {
1514
            have_nulls = true;
1515
            return 0;
1516
151k
        } else {
1517
151k
            field_types.insert(T);
1518
151k
            type_indexes.insert(T);
1519
151k
            return 0;
1520
151k
        }
1521
151k
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE36EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE37EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE23EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1506
297k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1507
        if constexpr (T == TYPE_ARRAY) {
1508
            size_t size = x.size();
1509
            for (size_t i = 0; i < size; ++i) {
1510
                apply_visitor(*this, x[i]);
1511
            }
1512
            return 0;
1513
        } else if constexpr (T == TYPE_NULL) {
1514
            have_nulls = true;
1515
            return 0;
1516
297k
        } else {
1517
297k
            field_types.insert(T);
1518
297k
            type_indexes.insert(T);
1519
297k
            return 0;
1520
297k
        }
1521
297k
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE15EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE10EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE41EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE17EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1506
127k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1507
127k
        if constexpr (T == TYPE_ARRAY) {
1508
127k
            size_t size = x.size();
1509
873k
            for (size_t i = 0; i < size; ++i) {
1510
745k
                apply_visitor(*this, x[i]);
1511
745k
            }
1512
127k
            return 0;
1513
        } else if constexpr (T == TYPE_NULL) {
1514
            have_nulls = true;
1515
            return 0;
1516
        } else {
1517
            field_types.insert(T);
1518
            type_indexes.insert(T);
1519
            return 0;
1520
        }
1521
127k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE16EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1506
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1507
        if constexpr (T == TYPE_ARRAY) {
1508
            size_t size = x.size();
1509
            for (size_t i = 0; i < size; ++i) {
1510
                apply_visitor(*this, x[i]);
1511
            }
1512
            return 0;
1513
        } else if constexpr (T == TYPE_NULL) {
1514
            have_nulls = true;
1515
            return 0;
1516
1
        } else {
1517
1
            field_types.insert(T);
1518
1
            type_indexes.insert(T);
1519
1
            return 0;
1520
1
        }
1521
1
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE18EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE32EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1506
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1507
        if constexpr (T == TYPE_ARRAY) {
1508
            size_t size = x.size();
1509
            for (size_t i = 0; i < size; ++i) {
1510
                apply_visitor(*this, x[i]);
1511
            }
1512
            return 0;
1513
        } else if constexpr (T == TYPE_NULL) {
1514
            have_nulls = true;
1515
            return 0;
1516
1
        } else {
1517
1
            field_types.insert(T);
1518
1
            type_indexes.insert(T);
1519
1
            return 0;
1520
1
        }
1521
1
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE28EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE29EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE20EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE30EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE35EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE22EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE19EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE24EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE31EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1506
26
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1507
        if constexpr (T == TYPE_ARRAY) {
1508
            size_t size = x.size();
1509
            for (size_t i = 0; i < size; ++i) {
1510
                apply_visitor(*this, x[i]);
1511
            }
1512
            return 0;
1513
        } else if constexpr (T == TYPE_NULL) {
1514
            have_nulls = true;
1515
            return 0;
1516
26
        } else {
1517
26
            field_types.insert(T);
1518
26
            type_indexes.insert(T);
1519
26
            return 0;
1520
26
        }
1521
26
    }
1522
77.7k
    void get_scalar_type(PrimitiveType* type) const {
1523
77.7k
        if (type_indexes.size() == 1) {
1524
            // Most cases will have only one type
1525
64.5k
            *type = *type_indexes.begin();
1526
64.5k
            return;
1527
64.5k
        }
1528
13.2k
        DataTypePtr data_type;
1529
13.2k
        get_least_supertype_jsonb(type_indexes, &data_type);
1530
13.2k
        *type = data_type->get_primitive_type();
1531
13.2k
    }
1532
77.7k
    bool contain_nulls() const { return have_nulls; }
1533
77.7k
    bool need_convert_field() const { return field_types.size() > 1; }
1534
1535
private:
1536
    phmap::flat_hash_set<PrimitiveType> type_indexes;
1537
    phmap::flat_hash_set<PrimitiveType> field_types;
1538
    bool have_nulls = false;
1539
};
1540
1541
template <typename Visitor>
1542
1.50M
void get_field_info_impl(const Field& field, FieldInfo* info) {
1543
1.50M
    Visitor to_scalar_type_visitor;
1544
1.50M
    apply_visitor(to_scalar_type_visitor, field);
1545
1.50M
    PrimitiveType type_id;
1546
1.50M
    to_scalar_type_visitor.get_scalar_type(&type_id);
1547
    // array item's dimension may missmatch, eg. [1, 2, [1, 2, 3]]
1548
1.50M
    *info = {type_id, to_scalar_type_visitor.contain_nulls(),
1549
1.50M
             to_scalar_type_visitor.need_convert_field(),
1550
1.50M
             apply_visitor(FieldVisitorToNumberOfDimensions(), field)};
1551
1.50M
}
_ZN5doris12variant_util19get_field_info_implINS0_24FieldVisitorToScalarTypeEEEvRKNS_5FieldEPNS_9FieldInfoE
Line
Count
Source
1542
77.7k
void get_field_info_impl(const Field& field, FieldInfo* info) {
1543
77.7k
    Visitor to_scalar_type_visitor;
1544
77.7k
    apply_visitor(to_scalar_type_visitor, field);
1545
77.7k
    PrimitiveType type_id;
1546
77.7k
    to_scalar_type_visitor.get_scalar_type(&type_id);
1547
    // array item's dimension may missmatch, eg. [1, 2, [1, 2, 3]]
1548
77.7k
    *info = {type_id, to_scalar_type_visitor.contain_nulls(),
1549
77.7k
             to_scalar_type_visitor.need_convert_field(),
1550
77.7k
             apply_visitor(FieldVisitorToNumberOfDimensions(), field)};
1551
77.7k
}
_ZN5doris12variant_util19get_field_info_implINS0_30SimpleFieldVisitorToScalarTypeEEEvRKNS_5FieldEPNS_9FieldInfoE
Line
Count
Source
1542
1.42M
void get_field_info_impl(const Field& field, FieldInfo* info) {
1543
1.42M
    Visitor to_scalar_type_visitor;
1544
1.42M
    apply_visitor(to_scalar_type_visitor, field);
1545
1.42M
    PrimitiveType type_id;
1546
1.42M
    to_scalar_type_visitor.get_scalar_type(&type_id);
1547
    // array item's dimension may missmatch, eg. [1, 2, [1, 2, 3]]
1548
1.42M
    *info = {type_id, to_scalar_type_visitor.contain_nulls(),
1549
1.42M
             to_scalar_type_visitor.need_convert_field(),
1550
1.42M
             apply_visitor(FieldVisitorToNumberOfDimensions(), field)};
1551
1.42M
}
1552
1553
1.50M
void get_field_info(const Field& field, FieldInfo* info) {
1554
1.50M
    if (field.is_complex_field()) {
1555
77.7k
        get_field_info_impl<FieldVisitorToScalarType>(field, info);
1556
1.42M
    } else {
1557
1.42M
        get_field_info_impl<SimpleFieldVisitorToScalarType>(field, info);
1558
1.42M
    }
1559
1.50M
}
1560
1561
bool generate_sub_column_info(const TabletSchema& schema, int32_t col_unique_id,
1562
                              const std::string& path,
1563
1.97k
                              TabletSchema::SubColumnInfo* sub_column_info) {
1564
1.97k
    const auto& parent_column = schema.column_by_uid(col_unique_id);
1565
1.97k
    std::function<void(const TabletColumn&, TabletColumn*)> generate_result_column =
1566
1.97k
            [&](const TabletColumn& from_column, TabletColumn* to_column) {
1567
35
                to_column->set_name(parent_column.name_lower_case() + "." + path);
1568
35
                to_column->set_type(from_column.type());
1569
35
                to_column->set_parent_unique_id(parent_column.unique_id());
1570
35
                bool is_typed = !parent_column.variant_enable_typed_paths_to_sparse();
1571
35
                to_column->set_path_info(
1572
35
                        PathInData(parent_column.name_lower_case() + "." + path, is_typed));
1573
35
                to_column->set_aggregation_method(parent_column.aggregation());
1574
35
                to_column->set_is_nullable(true);
1575
35
                to_column->set_parent_unique_id(parent_column.unique_id());
1576
35
                if (from_column.is_decimal()) {
1577
0
                    to_column->set_precision(from_column.precision());
1578
0
                }
1579
35
                to_column->set_frac(from_column.frac());
1580
1581
35
                if (from_column.is_array_type()) {
1582
2
                    TabletColumn nested_column;
1583
2
                    generate_result_column(*from_column.get_sub_columns()[0], &nested_column);
1584
2
                    to_column->add_sub_column(nested_column);
1585
2
                }
1586
35
            };
1587
1588
1.97k
    auto generate_index = [&](const std::string& pattern) {
1589
        // 1. find subcolumn's index
1590
33
        if (const auto& indexes = schema.inverted_index_by_field_pattern(col_unique_id, pattern);
1591
33
            !indexes.empty()) {
1592
6
            for (const auto& index : indexes) {
1593
6
                auto index_ptr = std::make_shared<TabletIndex>(*index);
1594
6
                index_ptr->set_escaped_escaped_index_suffix_path(
1595
6
                        sub_column_info->column.path_info_ptr()->get_path());
1596
6
                sub_column_info->indexes.emplace_back(std::move(index_ptr));
1597
6
            }
1598
6
        }
1599
        // 2. find parent column's index
1600
27
        else if (const auto parent_index = schema.inverted_indexs(col_unique_id);
1601
27
                 !parent_index.empty()) {
1602
0
            inherit_index(parent_index, sub_column_info->indexes, sub_column_info->column);
1603
27
        } else {
1604
27
            sub_column_info->indexes.clear();
1605
27
        }
1606
33
    };
1607
1608
1.97k
    const auto& sub_columns = parent_column.get_sub_columns();
1609
1.97k
    for (const auto& sub_column : sub_columns) {
1610
119
        const char* pattern = sub_column->name().c_str();
1611
119
        switch (sub_column->pattern_type()) {
1612
1
        case PatternTypePB::MATCH_NAME: {
1613
1
            if (strcmp(pattern, path.c_str()) == 0) {
1614
1
                generate_result_column(*sub_column, &sub_column_info->column);
1615
1
                generate_index(sub_column->name());
1616
1
                return true;
1617
1
            }
1618
0
            break;
1619
1
        }
1620
118
        case PatternTypePB::MATCH_NAME_GLOB: {
1621
118
            if (glob_match_re2(pattern, path)) {
1622
32
                generate_result_column(*sub_column, &sub_column_info->column);
1623
32
                generate_index(sub_column->name());
1624
32
                return true;
1625
32
            }
1626
86
            break;
1627
118
        }
1628
86
        default:
1629
0
            break;
1630
119
        }
1631
119
    }
1632
1.94k
    return false;
1633
1.97k
}
1634
1635
TabletSchemaSPtr VariantCompactionUtil::calculate_variant_extended_schema(
1636
0
        const std::vector<RowsetSharedPtr>& rowsets, const TabletSchemaSPtr& base_schema) {
1637
0
    if (rowsets.empty()) {
1638
0
        return nullptr;
1639
0
    }
1640
1641
0
    std::vector<TabletSchemaSPtr> schemas;
1642
0
    for (const auto& rs : rowsets) {
1643
0
        if (rs->num_segments() == 0) {
1644
0
            continue;
1645
0
        }
1646
0
        const auto& tablet_schema = rs->tablet_schema();
1647
0
        SegmentCacheHandle segment_cache;
1648
0
        auto st = SegmentLoader::instance()->load_segments(std::static_pointer_cast<BetaRowset>(rs),
1649
0
                                                           &segment_cache);
1650
0
        if (!st.ok()) {
1651
0
            return base_schema;
1652
0
        }
1653
0
        for (const auto& segment : segment_cache.get_segments()) {
1654
0
            TabletSchemaSPtr schema = tablet_schema->copy_without_variant_extracted_columns();
1655
0
            for (const auto& column : tablet_schema->columns()) {
1656
0
                if (!column->is_variant_type()) {
1657
0
                    continue;
1658
0
                }
1659
0
                std::shared_ptr<ColumnReader> column_reader;
1660
0
                OlapReaderStatistics stats;
1661
0
                st = segment->get_column_reader(column->unique_id(), &column_reader, &stats);
1662
0
                if (!st.ok()) {
1663
0
                    LOG(WARNING) << "Failed to get column reader for column: " << column->name()
1664
0
                                 << " error: " << st.to_string();
1665
0
                    continue;
1666
0
                }
1667
0
                if (!column_reader) {
1668
0
                    continue;
1669
0
                }
1670
1671
0
                CHECK(column_reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT);
1672
0
                auto* variant_column_reader =
1673
0
                        assert_cast<segment_v2::VariantColumnReader*>(column_reader.get());
1674
                // load external meta before getting subcolumn meta info
1675
0
                st = variant_column_reader->load_external_meta_once();
1676
0
                if (!st.ok()) {
1677
0
                    LOG(WARNING) << "Failed to load external meta for column: " << column->name()
1678
0
                                 << " error: " << st.to_string();
1679
0
                    continue;
1680
0
                }
1681
0
                const auto* subcolumn_meta_info = variant_column_reader->get_subcolumns_meta_info();
1682
0
                for (const auto& entry : *subcolumn_meta_info) {
1683
0
                    if (entry->path.empty()) {
1684
0
                        continue;
1685
0
                    }
1686
0
                    const std::string& column_name =
1687
0
                            column->name_lower_case() + "." + entry->path.get_path();
1688
0
                    const DataTypePtr& data_type = entry->data.file_column_type;
1689
0
                    PathInDataBuilder full_path_builder;
1690
0
                    auto full_path = full_path_builder.append(column->name_lower_case(), false)
1691
0
                                             .append(entry->path.get_parts(), false)
1692
0
                                             .build();
1693
0
                    TabletColumn subcolumn =
1694
0
                            get_column_by_type(data_type, column_name,
1695
0
                                               ExtraInfo {.unique_id = -1,
1696
0
                                                          .parent_unique_id = column->unique_id(),
1697
0
                                                          .path_info = full_path});
1698
0
                    schema->append_column(subcolumn);
1699
0
                }
1700
0
            }
1701
0
            schemas.emplace_back(schema);
1702
0
        }
1703
0
    }
1704
0
    TabletSchemaSPtr least_common_schema;
1705
0
    auto st = get_least_common_schema(schemas, base_schema, least_common_schema, false);
1706
0
    if (!st.ok()) {
1707
0
        return base_schema;
1708
0
    }
1709
0
    return least_common_schema;
1710
0
}
1711
1712
bool inherit_index(const std::vector<const TabletIndex*>& parent_indexes,
1713
                   TabletIndexes& subcolumns_indexes, FieldType column_type,
1714
1.00k
                   const std::string& suffix_path, bool is_array_nested_type) {
1715
1.00k
    if (parent_indexes.empty()) {
1716
983
        return false;
1717
983
    }
1718
20
    subcolumns_indexes.clear();
1719
    // bkd index or array index only need to inherit one index
1720
20
    if (field_is_numeric_type(column_type) ||
1721
20
        (is_array_nested_type &&
1722
13
         (field_is_numeric_type(column_type) || field_is_slice_type(column_type)))) {
1723
9
        auto index_ptr = std::make_shared<TabletIndex>(*parent_indexes[0]);
1724
9
        index_ptr->set_escaped_escaped_index_suffix_path(suffix_path);
1725
        // no need parse for bkd index or array index
1726
9
        index_ptr->remove_parser_and_analyzer();
1727
9
        subcolumns_indexes.emplace_back(std::move(index_ptr));
1728
9
        return true;
1729
9
    }
1730
    // string type need to inherit all indexes
1731
11
    else if (field_is_slice_type(column_type) && !is_array_nested_type) {
1732
10
        for (const auto& index : parent_indexes) {
1733
10
            auto index_ptr = std::make_shared<TabletIndex>(*index);
1734
10
            index_ptr->set_escaped_escaped_index_suffix_path(suffix_path);
1735
10
            subcolumns_indexes.emplace_back(std::move(index_ptr));
1736
10
        }
1737
9
        return true;
1738
9
    }
1739
2
    return false;
1740
20
}
1741
1742
bool inherit_index(const std::vector<const TabletIndex*>& parent_indexes,
1743
1.00k
                   TabletIndexes& subcolumns_indexes, const TabletColumn& column) {
1744
1.00k
    if (!column.is_extracted_column()) {
1745
3
        return false;
1746
3
    }
1747
1.00k
    if (column.is_array_type()) {
1748
14
        if (column.get_sub_columns().empty()) {
1749
0
            return false;
1750
0
        }
1751
14
        const TabletColumn* nested = column.get_sub_columns()[0].get();
1752
14
        while (nested != nullptr && nested->is_array_type()) {
1753
0
            if (nested->get_sub_columns().empty()) {
1754
0
                return false;
1755
0
            }
1756
0
            nested = nested->get_sub_columns()[0].get();
1757
0
        }
1758
14
        if (nested == nullptr) {
1759
0
            return false;
1760
0
        }
1761
14
        return inherit_index(parent_indexes, subcolumns_indexes, nested->type(),
1762
14
                             column.path_info_ptr()->get_path(), true);
1763
14
    }
1764
989
    return inherit_index(parent_indexes, subcolumns_indexes, column.type(),
1765
989
                         column.path_info_ptr()->get_path());
1766
1.00k
}
1767
1768
bool inherit_index(const std::vector<const TabletIndex*>& parent_indexes,
1769
0
                   TabletIndexes& subcolumns_indexes, const ColumnMetaPB& column_pb) {
1770
0
    if (!column_pb.has_column_path_info()) {
1771
0
        return false;
1772
0
    }
1773
0
    if (column_pb.type() == (int)FieldType::OLAP_FIELD_TYPE_ARRAY) {
1774
0
        if (column_pb.children_columns_size() == 0) {
1775
0
            return false;
1776
0
        }
1777
0
        const ColumnMetaPB* nested = &column_pb.children_columns(0);
1778
0
        while (nested != nullptr && nested->type() == (int)FieldType::OLAP_FIELD_TYPE_ARRAY) {
1779
0
            if (nested->children_columns_size() == 0) {
1780
0
                return false;
1781
0
            }
1782
0
            nested = &nested->children_columns(0);
1783
0
        }
1784
0
        if (nested == nullptr) {
1785
0
            return false;
1786
0
        }
1787
0
        return inherit_index(parent_indexes, subcolumns_indexes, (FieldType)nested->type(),
1788
0
                             column_pb.column_path_info().path(), true);
1789
0
    }
1790
0
    return inherit_index(parent_indexes, subcolumns_indexes, (FieldType)column_pb.type(),
1791
0
                         column_pb.column_path_info().path());
1792
0
}
1793
1794
// ============ Implementation from parse2column.cpp ============
1795
1796
/** Pool for objects that cannot be used from different threads simultaneously.
1797
  * Allows to create an object for each thread.
1798
  * Pool has unbounded size and objects are not destroyed before destruction of pool.
1799
  *
1800
  * Use it in cases when thread local storage is not appropriate
1801
  *  (when maximum number of simultaneously used objects is less
1802
  *   than number of running/sleeping threads, that has ever used object,
1803
  *   and creation/destruction of objects is expensive).
1804
  */
1805
template <typename T>
1806
class SimpleObjectPool {
1807
protected:
1808
    /// Hold all available objects in stack.
1809
    std::mutex mutex;
1810
    std::stack<std::unique_ptr<T>> stack;
1811
    /// Specialized deleter for std::unique_ptr.
1812
    /// Returns underlying pointer back to stack thus reclaiming its ownership.
1813
    struct Deleter {
1814
        SimpleObjectPool<T>* parent;
1815
12.6k
        Deleter(SimpleObjectPool<T>* parent_ = nullptr) : parent {parent_} {} /// NOLINT
1816
12.6k
        void operator()(T* owning_ptr) const {
1817
12.6k
            std::lock_guard lock {parent->mutex};
1818
12.6k
            parent->stack.emplace(owning_ptr);
1819
12.6k
        }
1820
    };
1821
1822
public:
1823
    using Pointer = std::unique_ptr<T, Deleter>;
1824
    /// Extracts and returns a pointer from the stack if it's not empty,
1825
    ///  creates a new one by calling provided f() otherwise.
1826
    template <typename Factory>
1827
12.6k
    Pointer get(Factory&& f) {
1828
12.6k
        std::unique_lock lock(mutex);
1829
12.6k
        if (stack.empty()) {
1830
1
            return {f(), this};
1831
1
        }
1832
12.6k
        auto object = stack.top().release();
1833
12.6k
        stack.pop();
1834
12.6k
        return std::unique_ptr<T, Deleter>(object, Deleter(this));
1835
12.6k
    }
variant_util.cpp:_ZN5doris12variant_util16SimpleObjectPoolINS_14JSONDataParserINS_14SimdJSONParserEEEE3getIZNS0_21parse_json_to_variantERNS_7IColumnERKNS_9StringRefEPS4_RKNS_11ParseConfigEE3$_0EESt10unique_ptrIS4_NS5_7DeleterEEOT_
Line
Count
Source
1827
12.4k
    Pointer get(Factory&& f) {
1828
12.4k
        std::unique_lock lock(mutex);
1829
12.4k
        if (stack.empty()) {
1830
1
            return {f(), this};
1831
1
        }
1832
12.4k
        auto object = stack.top().release();
1833
12.4k
        stack.pop();
1834
12.4k
        return std::unique_ptr<T, Deleter>(object, Deleter(this));
1835
12.4k
    }
variant_util.cpp:_ZN5doris12variant_util16SimpleObjectPoolINS_14JSONDataParserINS_14SimdJSONParserEEEE3getIZNS0_21parse_json_to_variantERNS_7IColumnERKNS_9ColumnStrIjEERKNS_11ParseConfigEE3$_0EESt10unique_ptrIS4_NS5_7DeleterEEOT_
Line
Count
Source
1827
221
    Pointer get(Factory&& f) {
1828
221
        std::unique_lock lock(mutex);
1829
221
        if (stack.empty()) {
1830
0
            return {f(), this};
1831
0
        }
1832
221
        auto object = stack.top().release();
1833
221
        stack.pop();
1834
221
        return std::unique_ptr<T, Deleter>(object, Deleter(this));
1835
221
    }
1836
    /// Like get(), but creates object using default constructor.
1837
    Pointer getDefault() {
1838
        return get([] { return new T; });
1839
    }
1840
};
1841
1842
SimpleObjectPool<JsonParser> parsers_pool;
1843
1844
using Node = typename ColumnVariant::Subcolumns::Node;
1845
1846
11.6k
static inline void append_binary_bytes(ColumnString::Chars& chars, const void* data, size_t size) {
1847
11.6k
    const auto old_size = chars.size();
1848
11.6k
    chars.resize(old_size + size);
1849
11.6k
    memcpy(chars.data() + old_size, reinterpret_cast<const char*>(data), size);
1850
11.6k
}
1851
1852
4.68k
static inline void append_binary_type(ColumnString::Chars& chars, FieldType type) {
1853
4.68k
    const uint8_t t = static_cast<uint8_t>(type);
1854
4.68k
    append_binary_bytes(chars, &t, sizeof(uint8_t));
1855
4.68k
}
1856
1857
2.23k
static inline void append_binary_sizet(ColumnString::Chars& chars, size_t v) {
1858
2.23k
    append_binary_bytes(chars, &v, sizeof(size_t));
1859
2.23k
}
1860
1861
4.68k
static void append_field_to_binary_chars(const Field& field, ColumnString::Chars& chars) {
1862
4.68k
    switch (field.get_type()) {
1863
0
    case PrimitiveType::TYPE_NULL: {
1864
0
        append_binary_type(chars, FieldType::OLAP_FIELD_TYPE_NONE);
1865
0
        return;
1866
0
    }
1867
2
    case PrimitiveType::TYPE_BOOLEAN: {
1868
2
        append_binary_type(chars,
1869
2
                           TabletColumn::get_field_type_by_type(PrimitiveType::TYPE_BOOLEAN));
1870
2
        const auto v = static_cast<UInt8>(field.get<PrimitiveType::TYPE_BOOLEAN>());
1871
2
        append_binary_bytes(chars, &v, sizeof(UInt8));
1872
2
        return;
1873
0
    }
1874
2.45k
    case PrimitiveType::TYPE_BIGINT: {
1875
2.45k
        append_binary_type(chars, TabletColumn::get_field_type_by_type(PrimitiveType::TYPE_BIGINT));
1876
2.45k
        const auto v = field.get<PrimitiveType::TYPE_BIGINT>();
1877
2.45k
        append_binary_bytes(chars, &v, sizeof(Int64));
1878
2.45k
        return;
1879
0
    }
1880
1
    case PrimitiveType::TYPE_LARGEINT: {
1881
1
        append_binary_type(chars,
1882
1
                           TabletColumn::get_field_type_by_type(PrimitiveType::TYPE_LARGEINT));
1883
1
        const auto v = field.get<PrimitiveType::TYPE_LARGEINT>();
1884
1
        append_binary_bytes(chars, &v, sizeof(int128_t));
1885
1
        return;
1886
0
    }
1887
1
    case PrimitiveType::TYPE_DOUBLE: {
1888
1
        append_binary_type(chars, TabletColumn::get_field_type_by_type(PrimitiveType::TYPE_DOUBLE));
1889
1
        const auto v = field.get<PrimitiveType::TYPE_DOUBLE>();
1890
1
        append_binary_bytes(chars, &v, sizeof(Float64));
1891
1
        return;
1892
0
    }
1893
2.22k
    case PrimitiveType::TYPE_STRING: {
1894
2.22k
        append_binary_type(chars, FieldType::OLAP_FIELD_TYPE_STRING);
1895
2.22k
        const auto& v = field.get<PrimitiveType::TYPE_STRING>();
1896
2.22k
        append_binary_sizet(chars, v.size());
1897
2.22k
        append_binary_bytes(chars, v.data(), v.size());
1898
2.22k
        return;
1899
0
    }
1900
0
    case PrimitiveType::TYPE_JSONB: {
1901
0
        append_binary_type(chars, FieldType::OLAP_FIELD_TYPE_JSONB);
1902
0
        const auto& v = field.get<PrimitiveType::TYPE_JSONB>();
1903
0
        append_binary_sizet(chars, v.get_size());
1904
0
        append_binary_bytes(chars, v.get_value(), v.get_size());
1905
0
        return;
1906
0
    }
1907
8
    case PrimitiveType::TYPE_ARRAY: {
1908
8
        append_binary_type(chars, FieldType::OLAP_FIELD_TYPE_ARRAY);
1909
8
        const auto& a = field.get<PrimitiveType::TYPE_ARRAY>();
1910
8
        append_binary_sizet(chars, a.size());
1911
13
        for (const auto& elem : a) {
1912
13
            append_field_to_binary_chars(elem, chars);
1913
13
        }
1914
8
        return;
1915
0
    }
1916
0
    default:
1917
0
        throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Unsupported field type {}",
1918
0
                               field.get_type());
1919
4.68k
    }
1920
4.68k
}
1921
template <typename ParserImpl>
1922
void parse_json_to_variant_impl(IColumn& column, const char* src, size_t length,
1923
80.6k
                                JSONDataParser<ParserImpl>* parser, const ParseConfig& config) {
1924
80.6k
    auto& column_variant = assert_cast<ColumnVariant&>(column);
1925
80.6k
    std::optional<ParseResult> result;
1926
    /// Treat empty string as an empty object
1927
    /// for better CAST from String to Object.
1928
80.6k
    if (length > 0) {
1929
80.6k
        result = parser->parse(src, length, config);
1930
80.6k
    } else {
1931
1
        result = ParseResult {};
1932
1
    }
1933
80.6k
    if (!result) {
1934
11
        VLOG_DEBUG << "failed to parse " << std::string_view(src, length) << ", length= " << length;
1935
11
        if (config::variant_throw_exeception_on_invalid_json) {
1936
0
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Failed to parse object {}",
1937
0
                                   std::string_view(src, length));
1938
0
        }
1939
        // Treat as string
1940
11
        PathInData root_path;
1941
11
        Field field = Field::create_field<TYPE_STRING>(String(src, length));
1942
11
        result = ParseResult {{root_path}, {field}};
1943
11
    }
1944
80.6k
    auto& [paths, values] = *result;
1945
80.6k
    assert(paths.size() == values.size());
1946
80.0k
    size_t old_num_rows = column_variant.rows();
1947
80.0k
    if (config.deprecated_enable_flatten_nested) {
1948
        // here we should check the paths in variant and paths in result,
1949
        // if two paths which same prefix have different structure, we should throw an exception
1950
3.00k
        std::vector<PathInData> check_paths;
1951
11.9k
        for (const auto& entry : column_variant.get_subcolumns()) {
1952
11.9k
            check_paths.push_back(entry->path);
1953
11.9k
        }
1954
3.00k
        check_paths.insert(check_paths.end(), paths.begin(), paths.end());
1955
3.00k
        THROW_IF_ERROR(check_variant_has_no_ambiguous_paths(check_paths));
1956
3.00k
    }
1957
80.0k
    auto [doc_value_data_paths, doc_value_data_values] =
1958
80.0k
            column_variant.get_doc_value_data_paths_and_values();
1959
80.0k
    auto& doc_value_data_offsets = column_variant.serialized_doc_value_column_offsets();
1960
1961
1.35M
    auto flush_defaults = [](ColumnVariant::Subcolumn* subcolumn) {
1962
1.35M
        const auto num_defaults = subcolumn->cur_num_of_defaults();
1963
1.35M
        if (num_defaults > 0) {
1964
104k
            subcolumn->insert_many_defaults(num_defaults);
1965
104k
            subcolumn->reset_current_num_of_defaults();
1966
104k
        }
1967
1.35M
    };
1968
1969
80.0k
    auto is_plain_path = [](const PathInData& path) {
1970
13
        for (const auto& part : path.get_parts()) {
1971
13
            if (part.is_nested || part.anonymous_array_level != 0) {
1972
0
                return false;
1973
0
            }
1974
13
        }
1975
9
        return true;
1976
9
    };
1977
1978
80.0k
    auto get_or_create_subcolumn = [&](const PathInData& path, size_t index_hint,
1979
1.35M
                                       const FieldInfo& field_info) -> ColumnVariant::Subcolumn* {
1980
1.35M
        auto* subcolumn = column_variant.get_subcolumn(path, index_hint);
1981
1.35M
        if (subcolumn == nullptr) {
1982
1.61k
            if (path.has_nested_part()) {
1983
8
                column_variant.add_nested_subcolumn(path, field_info, old_num_rows);
1984
1.60k
            } else {
1985
1.60k
                column_variant.add_sub_column(path, old_num_rows);
1986
1.60k
            }
1987
1.61k
            subcolumn = column_variant.get_subcolumn(path, index_hint);
1988
1.61k
        }
1989
1.35M
        if (!subcolumn) {
1990
0
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Failed to find sub column {}",
1991
0
                                   path.get_path());
1992
0
        }
1993
1.35M
        return subcolumn;
1994
1.35M
    };
1995
1996
1.35M
    auto normalize_plain_path = [&](const PathInData& path) {
1997
1.35M
        if (!config.check_duplicate_json_path || path.empty() || !is_plain_path(path)) {
1998
1.35M
            return path;
1999
1.35M
        }
2000
9
        return PathInData(path.get_path());
2001
1.35M
    };
2002
2003
80.0k
    auto insert_into_subcolumn = [&](size_t i,
2004
1.35M
                                     bool check_size_mismatch) -> ColumnVariant::Subcolumn* {
2005
1.35M
        FieldInfo field_info;
2006
1.35M
        get_field_info(values[i], &field_info);
2007
1.35M
        if (field_info.scalar_type_id == PrimitiveType::INVALID_TYPE) {
2008
104
            return nullptr;
2009
104
        }
2010
1.35M
        auto path = normalize_plain_path(paths[i]);
2011
1.35M
        auto* subcolumn = get_or_create_subcolumn(path, i, field_info);
2012
1.35M
        flush_defaults(subcolumn);
2013
1.35M
        if (check_size_mismatch && subcolumn->size() != old_num_rows) {
2014
1
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT,
2015
1
                                   "subcolumn {} size missmatched, may contains duplicated entry",
2016
1
                                   path.get_path());
2017
1
        }
2018
1.35M
        subcolumn->insert(std::move(values[i]), std::move(field_info));
2019
1.35M
        return subcolumn;
2020
1.35M
    };
2021
2022
80.0k
    switch (config.parse_to) {
2023
79.0k
    case ParseConfig::ParseTo::OnlySubcolumns:
2024
1.43M
        for (size_t i = 0; i < paths.size(); ++i) {
2025
1.35M
            insert_into_subcolumn(i, true);
2026
1.35M
        }
2027
79.0k
        break;
2028
1.02k
    case ParseConfig::ParseTo::OnlyDocValueColumn: {
2029
1.02k
        CHECK(column_variant.enable_doc_mode()) << "OnlyDocValueColumn requires doc mode enabled";
2030
1.02k
        std::vector<size_t> doc_item_indexes;
2031
1.02k
        doc_item_indexes.reserve(paths.size());
2032
1.02k
        phmap::flat_hash_set<StringRef, StringRefHash> seen_paths;
2033
1.02k
        seen_paths.reserve(paths.size());
2034
2035
5.69k
        for (size_t i = 0; i < paths.size(); ++i) {
2036
4.67k
            FieldInfo field_info;
2037
4.67k
            get_field_info(values[i], &field_info);
2038
4.67k
            if (paths[i].empty()) {
2039
0
                auto* subcolumn = column_variant.get_subcolumn(paths[i]);
2040
0
                DCHECK(subcolumn != nullptr);
2041
0
                flush_defaults(subcolumn);
2042
0
                subcolumn->insert(std::move(values[i]), std::move(field_info));
2043
0
                continue;
2044
0
            }
2045
4.67k
            if (field_info.scalar_type_id == PrimitiveType::INVALID_TYPE ||
2046
4.67k
                values[i].get_type() == PrimitiveType::TYPE_NULL) {
2047
0
                continue;
2048
0
            }
2049
4.67k
            const auto& path_str = paths[i].get_path();
2050
4.67k
            StringRef path_ref {path_str.data(), path_str.size()};
2051
4.67k
            if (UNLIKELY(!seen_paths.emplace(path_ref).second)) {
2052
0
                throw doris::Exception(ErrorCode::INVALID_ARGUMENT,
2053
0
                                       "may contains duplicated entry : {}",
2054
0
                                       std::string_view(path_str));
2055
0
            }
2056
4.67k
            doc_item_indexes.push_back(i);
2057
4.67k
        }
2058
2059
1.02k
        std::sort(doc_item_indexes.begin(), doc_item_indexes.end(),
2060
7.37k
                  [&](size_t l, size_t r) { return paths[l].get_path() < paths[r].get_path(); });
2061
4.67k
        for (const auto idx : doc_item_indexes) {
2062
4.67k
            const auto& path_str = paths[idx].get_path();
2063
4.67k
            doc_value_data_paths->insert_data(path_str.data(), path_str.size());
2064
4.67k
            auto& chars = doc_value_data_values->get_chars();
2065
4.67k
            append_field_to_binary_chars(values[idx], chars);
2066
4.67k
            doc_value_data_values->get_offsets().push_back(chars.size());
2067
4.67k
        }
2068
1.02k
    } break;
2069
80.0k
    }
2070
80.0k
    doc_value_data_offsets.push_back(doc_value_data_paths->size());
2071
    // /// Insert default values to missed subcolumns.
2072
80.0k
    const auto& subcolumns = column_variant.get_subcolumns();
2073
1.73M
    for (const auto& entry : subcolumns) {
2074
1.73M
        if (entry->data.size() == old_num_rows) {
2075
            // Handle nested paths differently from simple paths
2076
384k
            if (entry->path.has_nested_part()) {
2077
                // Try to insert default from nested, if failed, insert regular default
2078
0
                bool success = UNLIKELY(column_variant.try_insert_default_from_nested(entry));
2079
0
                if (!success) {
2080
0
                    entry->data.insert_default();
2081
0
                }
2082
384k
            } else {
2083
                // For non-nested paths, increment default counter
2084
384k
                entry->data.increment_default_counter();
2085
384k
            }
2086
384k
        }
2087
1.73M
    }
2088
80.0k
    column_variant.incr_num_rows();
2089
80.0k
    auto sparse_column = column_variant.get_sparse_column();
2090
80.0k
    if (sparse_column->size() == old_num_rows) {
2091
80.0k
        sparse_column->assume_mutable()->insert_default();
2092
80.0k
    }
2093
80.0k
#ifndef NDEBUG
2094
80.0k
    column_variant.check_consistency();
2095
80.0k
#endif
2096
80.0k
}
2097
2098
// exposed interfaces
2099
void parse_json_to_variant(IColumn& column, const StringRef& json, JsonParser* parser,
2100
12.4k
                           const ParseConfig& config) {
2101
12.4k
    if (parser) {
2102
0
        return parse_json_to_variant_impl(column, json.data, json.size, parser, config);
2103
12.4k
    } else {
2104
12.4k
        auto pool_parser = parsers_pool.get([] { return new JsonParser(); });
2105
12.4k
        return parse_json_to_variant_impl(column, json.data, json.size, pool_parser.get(), config);
2106
12.4k
    }
2107
12.4k
}
2108
2109
void parse_json_to_variant(IColumn& column, const ColumnString& raw_json_column,
2110
221
                           const ParseConfig& config) {
2111
221
    auto parser = parsers_pool.get([] { return new JsonParser(); });
2112
68.4k
    for (size_t i = 0; i < raw_json_column.size(); ++i) {
2113
68.1k
        StringRef raw_json = raw_json_column.get_data_at(i);
2114
68.1k
        parse_json_to_variant_impl(column, raw_json.data, raw_json.size, parser.get(), config);
2115
68.1k
    }
2116
221
    column.finalize();
2117
221
}
2118
2119
// parse the doc snapshot column to subcolumns
2120
0
void materialize_docs_to_subcolumns(ColumnVariant& column_variant) {
2121
0
    auto subcolumns = materialize_docs_to_subcolumns_map(column_variant);
2122
2123
0
    for (auto& entry : subcolumns) {
2124
0
        entry.second.finalize();
2125
0
        if (!column_variant.add_sub_column(PathInData(entry.first),
2126
0
                                           IColumn::mutate(entry.second.get_finalized_column_ptr()),
2127
0
                                           entry.second.get_least_common_type())) {
2128
0
            throw doris::Exception(ErrorCode::INTERNAL_ERROR,
2129
0
                                   "Failed to add subcolumn {}, which is from doc snapshot column",
2130
0
                                   entry.first);
2131
0
        }
2132
0
    }
2133
2134
0
    column_variant.finalize();
2135
0
}
2136
2137
// ============ Implementation from variant_util.cpp ============
2138
2139
phmap::flat_hash_map<std::string_view, ColumnVariant::Subcolumn> materialize_docs_to_subcolumns_map(
2140
7
        const ColumnVariant& variant, size_t expected_unique_paths) {
2141
7
    constexpr size_t kInitialPathReserve = 8192;
2142
7
    phmap::flat_hash_map<std::string_view, ColumnVariant::Subcolumn> subcolumns;
2143
2144
7
    const auto [column_key, column_value] = variant.get_doc_value_data_paths_and_values();
2145
7
    const auto& column_offsets = variant.serialized_doc_value_column_offsets();
2146
7
    const size_t num_rows = column_offsets.size();
2147
2148
7
    DCHECK_EQ(num_rows, variant.size()) << "doc snapshot offsets size mismatch with variant rows";
2149
2150
7
    subcolumns.reserve(expected_unique_paths != 0
2151
7
                               ? expected_unique_paths
2152
7
                               : std::min<size_t>(column_key->size(), kInitialPathReserve));
2153
2154
27
    for (size_t row = 0; row < num_rows; ++row) {
2155
20
        const size_t start = column_offsets[row - 1];
2156
20
        const size_t end = column_offsets[row];
2157
58
        for (size_t i = start; i < end; ++i) {
2158
38
            const auto& key = column_key->get_data_at(i);
2159
38
            const std::string_view path_sv(key.data, key.size);
2160
2161
38
            auto [it, inserted] =
2162
38
                    subcolumns.try_emplace(path_sv, ColumnVariant::Subcolumn {0, true, false});
2163
38
            auto& subcolumn = it->second;
2164
38
            if (inserted) {
2165
20
                subcolumn.insert_many_defaults(row);
2166
20
            } else if (subcolumn.size() != row) {
2167
4
                subcolumn.insert_many_defaults(row - subcolumn.size());
2168
4
            }
2169
38
            subcolumn.deserialize_from_binary_column(column_value, i);
2170
38
        }
2171
20
    }
2172
2173
20
    for (auto& [path, subcolumn] : subcolumns) {
2174
20
        if (subcolumn.size() != num_rows) {
2175
7
            subcolumn.insert_many_defaults(num_rows - subcolumn.size());
2176
7
        }
2177
20
    }
2178
2179
7
    return subcolumns;
2180
7
}
2181
2182
Status _parse_and_materialize_variant_columns(Block& block,
2183
                                              const std::vector<uint32_t>& variant_pos,
2184
150
                                              const std::vector<ParseConfig>& configs) {
2185
435
    for (size_t i = 0; i < variant_pos.size(); ++i) {
2186
285
        auto column_ref = block.get_by_position(variant_pos[i]).column;
2187
285
        bool is_nullable = column_ref->is_nullable();
2188
285
        MutableColumnPtr var_column = column_ref->assume_mutable();
2189
285
        if (is_nullable) {
2190
1
            const auto& nullable = assert_cast<const ColumnNullable&>(*column_ref);
2191
1
            var_column = nullable.get_nested_column_ptr()->assume_mutable();
2192
1
        }
2193
285
        auto& var = assert_cast<ColumnVariant&>(*var_column);
2194
285
        var_column->finalize();
2195
2196
285
        MutableColumnPtr variant_column;
2197
285
        if (!var.is_scalar_variant()) {
2198
            // already parsed
2199
279
            continue;
2200
279
        }
2201
2202
6
        VLOG_DEBUG << "parse scalar variant column: " << var.get_root_type()->get_name();
2203
6
        ColumnPtr scalar_root_column;
2204
6
        if (var.get_root_type()->get_primitive_type() == TYPE_JSONB) {
2205
            // TODO more efficient way to parse jsonb type, currently we just convert jsonb to
2206
            // json str and parse them into variant
2207
1
            RETURN_IF_ERROR(cast_column({var.get_root(), var.get_root_type(), ""},
2208
1
                                        var.get_root()->is_nullable()
2209
1
                                                ? make_nullable(std::make_shared<DataTypeString>())
2210
1
                                                : std::make_shared<DataTypeString>(),
2211
1
                                        &scalar_root_column));
2212
1
            if (scalar_root_column->is_nullable()) {
2213
1
                scalar_root_column = assert_cast<const ColumnNullable*>(scalar_root_column.get())
2214
1
                                             ->get_nested_column_ptr();
2215
1
            }
2216
5
        } else {
2217
5
            const auto& root = *var.get_root();
2218
5
            scalar_root_column =
2219
5
                    root.is_nullable()
2220
5
                            ? assert_cast<const ColumnNullable&>(root).get_nested_column_ptr()
2221
5
                            : var.get_root();
2222
5
        }
2223
2224
6
        if (scalar_root_column->is_column_string()) {
2225
6
            variant_column = ColumnVariant::create(0, var.enable_doc_mode());
2226
6
            parse_json_to_variant(*variant_column.get(),
2227
6
                                  assert_cast<const ColumnString&>(*scalar_root_column),
2228
6
                                  configs[i]);
2229
6
        } else {
2230
            // Root maybe other types rather than string like ColumnVariant(Int32).
2231
            // In this case, we should finlize the root and cast to JSON type
2232
0
            auto expected_root_type =
2233
0
                    make_nullable(std::make_shared<ColumnVariant::MostCommonType>());
2234
0
            var.ensure_root_node_type(expected_root_type);
2235
0
            variant_column = var.assume_mutable();
2236
0
        }
2237
2238
        // Wrap variant with nullmap if it is nullable
2239
6
        ColumnPtr result = variant_column->get_ptr();
2240
6
        if (is_nullable) {
2241
1
            const auto& null_map =
2242
1
                    assert_cast<const ColumnNullable&>(*column_ref).get_null_map_column_ptr();
2243
1
            result = ColumnNullable::create(result, null_map);
2244
1
        }
2245
6
        block.get_by_position(variant_pos[i]).column = result;
2246
6
    }
2247
150
    return Status::OK();
2248
150
}
2249
2250
Status parse_and_materialize_variant_columns(Block& block, const std::vector<uint32_t>& variant_pos,
2251
150
                                             const std::vector<ParseConfig>& configs) {
2252
150
    RETURN_IF_CATCH_EXCEPTION(
2253
150
            { return _parse_and_materialize_variant_columns(block, variant_pos, configs); });
2254
150
}
2255
2256
Status parse_and_materialize_variant_columns(Block& block, const TabletSchema& tablet_schema,
2257
142
                                             const std::vector<uint32_t>& column_pos) {
2258
142
    std::vector<uint32_t> variant_column_pos;
2259
142
    std::vector<uint32_t> variant_schema_pos;
2260
142
    variant_column_pos.reserve(column_pos.size());
2261
142
    variant_schema_pos.reserve(column_pos.size());
2262
824
    for (size_t block_pos = 0; block_pos < column_pos.size(); ++block_pos) {
2263
682
        const uint32_t schema_pos = column_pos[block_pos];
2264
682
        const auto& column = tablet_schema.column(schema_pos);
2265
682
        if (column.is_variant_type()) {
2266
277
            variant_column_pos.push_back(schema_pos);
2267
277
            variant_schema_pos.push_back(schema_pos);
2268
277
        }
2269
682
    }
2270
2271
142
    if (variant_column_pos.empty()) {
2272
0
        return Status::OK();
2273
0
    }
2274
2275
142
    std::vector<ParseConfig> configs(variant_column_pos.size());
2276
419
    for (size_t i = 0; i < variant_column_pos.size(); ++i) {
2277
        // Deprecated legacy flatten-nested switch. Distinct from variant_enable_nested_group.
2278
277
        configs[i].deprecated_enable_flatten_nested =
2279
277
                tablet_schema.deprecated_variant_flatten_nested();
2280
277
        configs[i].check_duplicate_json_path = config::variant_enable_duplicate_json_path_check;
2281
277
        const auto& column = tablet_schema.column(variant_schema_pos[i]);
2282
277
        if (!column.is_variant_type()) {
2283
0
            return Status::InternalError("column is not variant type, column name: {}",
2284
0
                                         column.name());
2285
0
        }
2286
        // if doc mode is not enabled, no need to parse to doc value column
2287
277
        if (!column.variant_enable_doc_mode()) {
2288
277
            configure_decimal_number_preserve_paths(column, &configs[i]);
2289
277
            configs[i].parse_to = ParseConfig::ParseTo::OnlySubcolumns;
2290
277
            continue;
2291
277
        }
2292
2293
0
        configs[i].parse_to = ParseConfig::ParseTo::OnlyDocValueColumn;
2294
0
    }
2295
2296
142
    RETURN_IF_ERROR(parse_and_materialize_variant_columns(block, variant_column_pos, configs));
2297
142
    return Status::OK();
2298
142
}
2299
2300
} // namespace doris::variant_util