Coverage Report

Created: 2026-07-17 19:45

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