Coverage Report

Created: 2026-06-04 13:50

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