Coverage Report

Created: 2026-06-17 03:24

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