Coverage Report

Created: 2026-07-19 20:06

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.21k
PathInData make_full_subcolumn_path(const TabletColumnPtr& parent_column, std::string_view path) {
111
1.21k
    if (!path.empty()) {
112
1.21k
        return PathInData(parent_column->name_lower_case() + "." + std::string(path));
113
1.21k
    }
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.21k
}
120
121
void append_empty_key_subcolumn_from_stats(TabletSchema::PathsSetInfo& paths_set_info,
122
                                           const TabletColumnPtr& parent_column,
123
15
                                           TabletSchemaSPtr& output_schema) {
124
15
    if (!paths_set_info.sub_path_set.contains("") || paths_set_info.sparse_path_set.contains("") ||
125
15
        paths_set_info.subcolumn_indexes.contains("")) {
126
14
        return;
127
14
    }
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.94k
inline void append_escaped_regex_char(std::string* regex_output, char ch) {
147
2.94k
    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.88k
    default:
166
2.88k
        regex_output->push_back(ch);
167
2.88k
        break;
168
2.94k
    }
169
2.94k
}
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
212k
std::shared_ptr<RE2> get_or_build_re2(const std::string& glob_pattern) {
184
212k
    {
185
212k
        std::lock_guard<std::mutex> lock(g_glob_regex_cache_mutex);
186
212k
        auto it = g_glob_regex_cache.find(glob_pattern);
187
212k
        if (it != g_glob_regex_cache.end()) {
188
212k
            g_glob_regex_cache_lru.splice(g_glob_regex_cache_lru.begin(), g_glob_regex_cache_lru,
189
212k
                                          it->second.lru_it);
190
212k
            return it->second.re2;
191
212k
        }
192
212k
    }
193
18.4E
    std::string regex_pattern;
194
18.4E
    Status st = glob_to_regex(glob_pattern, &regex_pattern);
195
18.4E
    if (!st.ok()) {
196
2
        return nullptr;
197
2
    }
198
18.4E
    auto compiled = std::make_shared<RE2>(regex_pattern);
199
18.4E
    if (!compiled->ok()) {
200
3
        return nullptr;
201
3
    }
202
18.4E
    {
203
18.4E
        std::lock_guard<std::mutex> lock(g_glob_regex_cache_mutex);
204
18.4E
        auto it = g_glob_regex_cache.find(glob_pattern);
205
18.4E
        if (it != g_glob_regex_cache.end()) {
206
3
            g_glob_regex_cache_lru.splice(g_glob_regex_cache_lru.begin(), g_glob_regex_cache_lru,
207
3
                                          it->second.lru_it);
208
3
            return it->second.re2;
209
3
        }
210
18.4E
        g_glob_regex_cache_lru.push_front(glob_pattern);
211
18.4E
        g_glob_regex_cache.emplace(glob_pattern,
212
18.4E
                                   GlobRegexCacheEntry {compiled, g_glob_regex_cache_lru.begin()});
213
18.4E
        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
18.4E
    }
219
0
    return compiled;
220
18.4E
}
221
222
// Convert a restricted glob pattern into a regex.
223
// Supported: '*', '?', '[...]', '\\' escape. Others are treated as literals.
224
319
Status glob_to_regex(const std::string& glob_pattern, std::string* regex_pattern) {
225
319
    regex_pattern->clear();
226
319
    regex_pattern->append("^");
227
319
    bool is_escaped = false;
228
319
    size_t pattern_length = glob_pattern.size();
229
3.38k
    for (size_t index = 0; index < pattern_length; ++index) {
230
3.07k
        char current_char = glob_pattern[index];
231
3.07k
        if (is_escaped) {
232
10
            append_escaped_regex_char(regex_pattern, current_char);
233
10
            is_escaped = false;
234
10
            continue;
235
10
        }
236
3.06k
        if (current_char == '\\') {
237
14
            is_escaped = true;
238
14
            continue;
239
14
        }
240
3.05k
        if (current_char == '*') {
241
76
            regex_pattern->append(".*");
242
76
            continue;
243
76
        }
244
2.97k
        if (current_char == '?') {
245
15
            regex_pattern->append(".");
246
15
            continue;
247
15
        }
248
2.95k
        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.92k
        append_escaped_regex_char(regex_pattern, current_char);
286
2.92k
    }
287
315
    if (is_escaped) {
288
4
        append_escaped_regex_char(regex_pattern, '\\');
289
4
    }
290
315
    regex_pattern->append("$");
291
315
    return Status::OK();
292
319
}
293
294
212k
bool glob_match_re2(const std::string& glob_pattern, const std::string& candidate_path) {
295
212k
    auto compiled = get_or_build_re2(glob_pattern);
296
212k
    if (compiled == nullptr) {
297
5
        return false;
298
5
    }
299
212k
    return RE2::FullMatch(candidate_path, *compiled);
300
212k
}
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
837
        const std::unordered_map<int32_t, VariantExtendedInfo>& uid_to_variant_extended_info) {
317
837
    const auto info_it = uid_to_variant_extended_info.find(column->unique_id());
318
837
    return column->variant_enable_nested_group() ||
319
865
           (info_it != uid_to_variant_extended_info.end() && info_it->second.has_nested_group);
320
837
}
321
322
std::unordered_set<int32_t> collect_nested_group_compaction_root_uids(
323
        const TabletSchemaSPtr& target,
324
11.4k
        const std::unordered_map<int32_t, VariantExtendedInfo>& uid_to_variant_extended_info) {
325
11.4k
    std::unordered_set<int32_t> root_uids;
326
114k
    for (const TabletColumnPtr& column : target->columns()) {
327
114k
        if (column->is_variant_type() && should_materialize_nested_group_regular_subcolumns(
328
838
                                                 column, uid_to_variant_extended_info)) {
329
1
            root_uids.insert(column->unique_id());
330
1
        }
331
114k
    }
332
11.4k
    return root_uids;
333
11.4k
}
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
86.5k
DataTypePtr get_base_type_of_array(const DataTypePtr& type) {
361
    /// Get raw pointers to avoid extra copying of type pointers.
362
86.5k
    const DataTypeArray* last_array = nullptr;
363
86.5k
    const auto* current_type = type.get();
364
86.5k
    if (const auto* nullable = typeid_cast<const DataTypeNullable*>(current_type)) {
365
86.5k
        current_type = nullable->get_nested_type().get();
366
86.5k
    }
367
89.7k
    while (const auto* type_array = typeid_cast<const DataTypeArray*>(current_type)) {
368
3.22k
        current_type = type_array->get_nested_type().get();
369
3.22k
        last_array = type_array;
370
3.22k
        if (const auto* nullable = typeid_cast<const DataTypeNullable*>(current_type)) {
371
3.22k
            current_type = nullable->get_nested_type().get();
372
3.22k
        }
373
3.22k
    }
374
86.5k
    return last_array ? last_array->get_nested_type() : type;
375
86.5k
}
376
377
942k
Status cast_column(const ColumnWithTypeAndName& arg, const DataTypePtr& type, ColumnPtr* result) {
378
942k
    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
942k
    if (type->get_primitive_type() == TYPE_VARIANT) {
385
        // If source column is variant, so the nullable info is different from dst column
386
13.0k
        if (arg.type->get_primitive_type() == TYPE_VARIANT) {
387
140
            *result = type->is_nullable() ? make_nullable(arg.column) : remove_nullable(arg.column);
388
140
            return Status::OK();
389
140
        }
390
        // set variant root column/type to from column/type
391
13.0k
        CHECK(is_column_nullable(*arg.column));
392
12.8k
        auto to_type = remove_nullable(type);
393
12.8k
        const auto& data_type_object = assert_cast<const DataTypeVariant&>(*to_type);
394
12.8k
        auto variant = ColumnVariant::create(data_type_object.variant_max_subcolumns_count(),
395
12.8k
                                             data_type_object.enable_doc_mode());
396
397
12.8k
        variant->create_root(arg.type, IColumn::mutate(arg.column));
398
12.8k
        ColumnPtr nullable = ColumnNullable::create(
399
12.8k
                variant->get_ptr(),
400
12.8k
                assert_cast<const ColumnNullable*>(arg.column.get())->get_null_map_column_ptr());
401
18.4E
        *result = type->is_nullable() ? nullable : variant->get_ptr();
402
12.8k
        return Status::OK();
403
13.0k
    }
404
405
929k
    auto function = SimpleFunctionFactory::instance().get_function("CAST", arguments, type);
406
929k
    if (!function) {
407
0
        return Status::InternalError("Not found cast function {} to {}", arg.type->get_name(),
408
0
                                     type->get_name());
409
0
    }
410
929k
    Block tmp_block {arguments};
411
929k
    uint32_t result_column = cast_set<uint32_t>(tmp_block.columns());
412
929k
    RuntimeState state;
413
929k
    auto ctx = FunctionContext::create_context(&state, {}, {});
414
415
929k
    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
923k
    ctx->set_string_as_jsonb_string(true);
425
923k
    ctx->set_jsonb_string_as_string(true);
426
923k
    tmp_block.insert({nullptr, type, arg.name});
427
    // TODO(lihangyu): we should handle this error in strict mode
428
923k
    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
923k
    *result = tmp_block.get_by_position(result_column).column->convert_to_full_column_if_const();
436
923k
    VLOG_DEBUG << fmt::format("{} before convert {}, after convert {}", arg.name,
437
11
                              arg.column->get_name(), (*result)->get_name());
438
923k
    return Status::OK();
439
923k
}
440
441
33
ColumnPtr jsonb_root_to_json_string_column(const IColumn& root) {
442
33
    auto root_column = root.convert_to_full_column_if_const();
443
33
    const IColumn* jsonb_column = root_column.get();
444
33
    const NullMap* null_map = nullptr;
445
33
    if (root_column->is_nullable()) {
446
28
        const auto& nullable = assert_cast<const ColumnNullable&>(*root_column);
447
28
        jsonb_column = &nullable.get_nested_column();
448
28
        null_map = &nullable.get_null_map_data();
449
28
    }
450
451
33
    const auto& column = assert_cast<const ColumnString&>(*jsonb_column);
452
33
    auto result = ColumnString::create();
453
33
    result->reserve(column.size());
454
120
    for (size_t i = 0; i < column.size(); ++i) {
455
87
        if (null_map != nullptr && (*null_map)[i]) {
456
14
            result->insert_default();
457
14
            continue;
458
14
        }
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
33
    return result->get_ptr();
470
33
}
471
472
void get_column_by_type(const DataTypePtr& data_type, const std::string& name, TabletColumn& column,
473
178k
                        const ExtraInfo& ext_info) {
474
178k
    column.set_name(name);
475
178k
    column.set_type(data_type->get_storage_field_type());
476
178k
    if (ext_info.unique_id >= 0) {
477
4
        column.set_unique_id(ext_info.unique_id);
478
4
    }
479
178k
    if (ext_info.parent_unique_id >= 0) {
480
85.8k
        column.set_parent_unique_id(ext_info.parent_unique_id);
481
85.8k
    }
482
178k
    if (!ext_info.path_info.empty()) {
483
85.8k
        column.set_path_info(ext_info.path_info);
484
85.8k
    }
485
178k
    if (data_type->is_nullable()) {
486
89.1k
        const auto& real_type = static_cast<const DataTypeNullable&>(*data_type);
487
89.1k
        column.set_is_nullable(true);
488
89.1k
        get_column_by_type(real_type.get_nested_type(), name, column, {});
489
89.1k
        return;
490
89.1k
    }
491
89.1k
    if (data_type->get_primitive_type() == PrimitiveType::TYPE_ARRAY) {
492
3.25k
        TabletColumn child;
493
3.25k
        get_column_by_type(assert_cast<const DataTypeArray*>(data_type.get())->get_nested_type(),
494
3.25k
                           "", child, {});
495
3.25k
        column.set_length(TabletColumn::get_field_length_by_type(TPrimitiveType::ARRAY, 0));
496
3.25k
        column.add_sub_column(child);
497
3.25k
        return;
498
3.25k
    }
499
85.8k
    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
85.8k
    if (is_string_type(data_type->get_primitive_type()) ||
507
85.8k
        data_type->get_primitive_type() == TYPE_JSONB) {
508
37.0k
        column.set_length(INT_MAX);
509
37.0k
        return;
510
37.0k
    }
511
512
48.7k
    PrimitiveType type = data_type->get_primitive_type();
513
48.7k
    if (is_int_or_bool(type) || is_string_type(type) || is_float_or_double(type) || is_ip(type) ||
514
48.7k
        is_date_or_datetime(type) || type == PrimitiveType::TYPE_DATEV2) {
515
48.6k
        column.set_length(cast_set<int32_t>(data_type->get_size_of_value_in_memory()));
516
48.6k
        return;
517
48.6k
    }
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
84.9k
                                const ExtraInfo& ext_info) {
537
84.9k
    TabletColumn result;
538
84.9k
    get_column_by_type(data_type, name, result, ext_info);
539
84.9k
    return result;
540
84.9k
}
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.85k
Status check_variant_has_no_ambiguous_paths(const PathsInData& tuple_paths) {
563
    // Group paths by their string representation to reduce comparisons
564
4.85k
    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.84k
    return Status::OK();
594
4.85k
}
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.81k
                                    std::set<PathInData>* path_set) {
600
1.81k
    PathsInData tuple_paths;
601
1.81k
    DataTypes tuple_types;
602
1.81k
    CHECK(common_schema.use_count() == 1);
603
    // Get the least common type for all paths.
604
1.81k
    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.81k
    CHECK_EQ(tuple_paths.size(), tuple_types.size());
631
632
    // Append all common type columns of this variant
633
2.79k
    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.81k
    return Status::OK();
656
1.81k
}
657
658
Status update_least_common_schema(const std::vector<TabletSchemaSPtr>& schemas,
659
                                  TabletSchemaSPtr& common_schema, int32_t variant_col_unique_id,
660
1.80k
                                  std::set<PathInData>* path_set) {
661
1.80k
    std::map<std::string, TabletColumnPtr> typed_columns;
662
1.80k
    for (const TabletColumnPtr& col :
663
7.91k
         common_schema->column_by_uid(variant_col_unique_id).get_sub_columns()) {
664
7.91k
        typed_columns[col->name()] = col;
665
7.91k
    }
666
    // Types of subcolumns by path from all tuples.
667
1.80k
    std::map<PathInData, DataTypes> subcolumns_types;
668
669
    // Collect all paths first to enable batch checking
670
1.80k
    std::vector<PathInData> all_paths;
671
672
2.00k
    for (const TabletSchemaSPtr& schema : schemas) {
673
6.54k
        for (const TabletColumnPtr& col : schema->columns()) {
674
            // Get subcolumns of this variant
675
6.54k
            if (col->has_path_info() && col->parent_unique_id() >= 0 &&
676
6.54k
                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
6.54k
        }
682
2.00k
    }
683
684
    // Batch check for conflicts
685
1.80k
    RETURN_IF_ERROR(check_variant_has_no_ambiguous_paths(all_paths));
686
687
1.80k
    return update_least_schema_internal(subcolumns_types, common_schema, variant_col_unique_id,
688
1.80k
                                        typed_columns, path_set);
689
1.80k
}
690
691
// Keep variant subcolumn BF support aligned with FE DDL checks.
692
94.7k
bool is_bf_supported_by_fe_for_variant_subcolumn(FieldType type) {
693
94.7k
    switch (type) {
694
91
    case FieldType::OLAP_FIELD_TYPE_SMALLINT:
695
509
    case FieldType::OLAP_FIELD_TYPE_INT:
696
39.0k
    case FieldType::OLAP_FIELD_TYPE_BIGINT:
697
39.2k
    case FieldType::OLAP_FIELD_TYPE_LARGEINT:
698
39.2k
    case FieldType::OLAP_FIELD_TYPE_CHAR:
699
39.2k
    case FieldType::OLAP_FIELD_TYPE_VARCHAR:
700
75.2k
    case FieldType::OLAP_FIELD_TYPE_STRING:
701
75.2k
    case FieldType::OLAP_FIELD_TYPE_DATE:
702
75.2k
    case FieldType::OLAP_FIELD_TYPE_DATETIME:
703
75.4k
    case FieldType::OLAP_FIELD_TYPE_DATEV2:
704
75.7k
    case FieldType::OLAP_FIELD_TYPE_DATETIMEV2:
705
75.7k
    case FieldType::OLAP_FIELD_TYPE_TIMESTAMPTZ:
706
75.7k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL:
707
75.7k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL32:
708
75.9k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL64:
709
76.1k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL128I:
710
76.2k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL256:
711
76.4k
    case FieldType::OLAP_FIELD_TYPE_IPV4:
712
76.5k
    case FieldType::OLAP_FIELD_TYPE_IPV6:
713
76.5k
        return true;
714
18.2k
    default:
715
18.2k
        return false;
716
94.7k
    }
717
94.7k
}
718
719
void inherit_column_attributes(const TabletColumn& source, TabletColumn& target,
720
94.7k
                               TabletSchemaSPtr* target_schema) {
721
94.7k
    if (!target.is_extracted_column()) {
722
0
        return;
723
0
    }
724
94.7k
    target.set_aggregation_method(source.aggregation());
725
726
    // 1. bloom filter
727
94.7k
    if (is_bf_supported_by_fe_for_variant_subcolumn(target.type())) {
728
76.5k
        target.set_is_bf_column(source.is_bf_column());
729
76.5k
    }
730
731
94.7k
    if (!target_schema) {
732
88.1k
        return;
733
88.1k
    }
734
735
    // 2. inverted index
736
6.64k
    TabletIndexes indexes_to_add;
737
6.64k
    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.64k
    if (target.is_variant_type()) {
741
5.77k
        for (auto& index : source_indexes) {
742
409
            auto index_info = std::make_shared<TabletIndex>(*index);
743
409
            index_info->set_escaped_escaped_index_suffix_path(target.path_info_ptr()->get_path());
744
409
            indexes_to_add.emplace_back(std::move(index_info));
745
409
        }
746
5.77k
    } else {
747
879
        inherit_index(source_indexes, indexes_to_add, target);
748
879
    }
749
6.64k
    auto target_indexes = (*target_schema)
750
6.64k
                                  ->inverted_indexs(target.parent_unique_id(),
751
6.64k
                                                    target.path_info_ptr()->get_path());
752
6.74k
    if (target_indexes.empty()) {
753
6.74k
        for (auto& index_info : indexes_to_add) {
754
422
            (*target_schema)->append_index(std::move(*index_info));
755
422
        }
756
6.74k
    }
757
758
    // 3. TODO: gnragm bf index
759
6.64k
}
760
761
7.98k
void inherit_column_attributes(TabletSchemaSPtr& schema) {
762
    // Add index meta if extracted column is missing index meta
763
98.0k
    for (size_t i = 0; i < schema->num_columns(); ++i) {
764
90.0k
        TabletColumn& col = schema->mutable_column(i);
765
90.0k
        if (!col.is_extracted_column()) {
766
83.3k
            continue;
767
83.3k
        }
768
6.71k
        if (schema->field_index(col.parent_unique_id()) == -1) {
769
            // parent column is missing, maybe dropped
770
0
            continue;
771
0
        }
772
6.71k
        inherit_column_attributes(schema->column_by_uid(col.parent_unique_id()), col, &schema);
773
6.71k
    }
774
7.98k
}
775
776
Status get_least_common_schema(const std::vector<TabletSchemaSPtr>& schemas,
777
                               const TabletSchemaSPtr& base_schema, TabletSchemaSPtr& output_schema,
778
1.77k
                               bool check_schema_size) {
779
1.77k
    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.77k
    auto build_schema_without_extracted_columns = [&](const TabletSchemaSPtr& base_schema) {
784
1.77k
        output_schema = std::make_shared<TabletSchema>();
785
        // not copy columns but only shadow copy other attributes
786
1.77k
        output_schema->shawdow_copy_without_columns(*base_schema);
787
        // Get all columns without extracted columns and collect variant col unique id
788
4.71k
        for (const TabletColumnPtr& col : base_schema->columns()) {
789
4.71k
            if (col->is_variant_type()) {
790
1.80k
                variant_column_unique_id.push_back(col->unique_id());
791
1.80k
            }
792
4.71k
            if (!col->is_extracted_column()) {
793
4.20k
                output_schema->append_column(*col);
794
4.20k
            }
795
4.71k
        }
796
1.77k
    };
797
1.77k
    if (base_schema == nullptr) {
798
        // Pick tablet schema with max schema version
799
324
        auto max_version_schema =
800
324
                *std::max_element(schemas.cbegin(), schemas.cend(),
801
1.42k
                                  [](const TabletSchemaSPtr a, const TabletSchemaSPtr b) {
802
1.42k
                                      return a->schema_version() < b->schema_version();
803
1.42k
                                  });
804
324
        CHECK(max_version_schema);
805
324
        build_schema_without_extracted_columns(max_version_schema);
806
1.44k
    } else {
807
        // use input base_schema schema as base schema
808
1.44k
        build_schema_without_extracted_columns(base_schema);
809
1.44k
    }
810
811
1.81k
    for (int32_t unique_id : variant_column_unique_id) {
812
1.81k
        std::set<PathInData> path_set;
813
1.81k
        RETURN_IF_ERROR(update_least_common_schema(schemas, output_schema, unique_id, &path_set));
814
1.81k
    }
815
816
1.77k
    inherit_column_attributes(output_schema);
817
1.77k
    if (check_schema_size &&
818
1.77k
        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.77k
    return Status::OK();
824
1.77k
}
825
826
// sort by paths in lexicographical order
827
2.15k
ColumnVariant::Subcolumns get_sorted_subcolumns(const ColumnVariant::Subcolumns& subcolumns) {
828
    // sort by paths in lexicographical order
829
2.15k
    ColumnVariant::Subcolumns sorted = subcolumns;
830
191k
    std::sort(sorted.begin(), sorted.end(), [](const auto& lhsItem, const auto& rhsItem) {
831
191k
        return lhsItem->path < rhsItem->path;
832
191k
    });
833
2.15k
    return sorted;
834
2.15k
}
835
836
bool has_schema_index_diff(const TabletSchema* new_schema, const TabletSchema* old_schema,
837
17.0k
                           int32_t new_col_idx, int32_t old_col_idx) {
838
17.0k
    const auto& column_new = new_schema->column(new_col_idx);
839
17.0k
    const auto& column_old = old_schema->column(old_col_idx);
840
841
17.0k
    if (column_new.is_bf_column() != column_old.is_bf_column()) {
842
94
        return true;
843
94
    }
844
845
16.9k
    auto new_schema_inverted_indexs = new_schema->inverted_indexs(column_new);
846
16.9k
    auto old_schema_inverted_indexs = old_schema->inverted_indexs(column_old);
847
848
16.9k
    if (new_schema_inverted_indexs.size() != old_schema_inverted_indexs.size()) {
849
705
        return true;
850
705
    }
851
852
16.6k
    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
20
            return true;
855
20
        }
856
390
    }
857
858
16.2k
    return false;
859
16.2k
}
860
861
1.80k
TabletColumn create_sparse_column(const TabletColumn& variant) {
862
1.80k
    TabletColumn res;
863
1.80k
    res.set_name(variant.name_lower_case() + "." + SPARSE_COLUMN_PATH);
864
1.80k
    res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
865
1.80k
    res.set_aggregation_method(variant.aggregation());
866
1.80k
    res.set_path_info(PathInData {variant.name_lower_case() + "." + SPARSE_COLUMN_PATH});
867
1.80k
    res.set_parent_unique_id(variant.unique_id());
868
    // set default value to "NULL" DefaultColumnIterator will call insert_many_defaults
869
1.80k
    res.set_default_value("NULL");
870
1.80k
    TabletColumn child_tcolumn;
871
1.80k
    child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
872
1.80k
    res.add_sub_column(child_tcolumn);
873
1.80k
    res.add_sub_column(child_tcolumn);
874
1.80k
    return res;
875
1.80k
}
876
877
27.6k
TabletColumn create_sparse_shard_column(const TabletColumn& variant, int bucket_index) {
878
27.6k
    TabletColumn res;
879
27.6k
    std::string name = variant.name_lower_case() + "." + SPARSE_COLUMN_PATH + ".b" +
880
27.6k
                       std::to_string(bucket_index);
881
27.6k
    res.set_name(name);
882
27.6k
    res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
883
27.6k
    res.set_aggregation_method(variant.aggregation());
884
27.6k
    res.set_parent_unique_id(variant.unique_id());
885
27.6k
    res.set_default_value("NULL");
886
27.6k
    PathInData path(name);
887
27.6k
    res.set_path_info(path);
888
27.6k
    TabletColumn child_tcolumn;
889
27.6k
    child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
890
27.6k
    res.add_sub_column(child_tcolumn);
891
27.6k
    res.add_sub_column(child_tcolumn);
892
27.6k
    return res;
893
27.6k
}
894
895
6.60k
TabletColumn create_doc_value_column(const TabletColumn& variant, int bucket_index) {
896
6.60k
    TabletColumn res;
897
6.60k
    std::string name = variant.name_lower_case() + "." + DOC_VALUE_COLUMN_PATH + ".b" +
898
6.60k
                       std::to_string(bucket_index);
899
6.60k
    res.set_name(name);
900
6.60k
    res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
901
6.60k
    res.set_aggregation_method(variant.aggregation());
902
6.60k
    res.set_parent_unique_id(variant.unique_id());
903
6.60k
    res.set_default_value("NULL");
904
6.60k
    res.set_path_info(PathInData {name});
905
906
6.60k
    TabletColumn child_tcolumn;
907
6.60k
    child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
908
6.60k
    res.add_sub_column(child_tcolumn);
909
6.60k
    res.add_sub_column(child_tcolumn);
910
6.60k
    return res;
911
6.60k
}
912
913
93.1k
uint32_t variant_binary_shard_of(const StringRef& path, uint32_t bucket_num) {
914
93.1k
    if (bucket_num <= 1) return 0;
915
79.5k
    SipHash hash;
916
79.5k
    hash.update(path.data, path.size);
917
79.5k
    uint64_t h = hash.get64();
918
79.5k
    return static_cast<uint32_t>(h % bucket_num);
919
93.1k
}
920
921
Status VariantCompactionUtil::aggregate_path_to_stats(
922
        const RowsetSharedPtr& rs,
923
3.23k
        std::unordered_map<int32_t, PathToNoneNullValues>* uid_to_path_stats) {
924
3.23k
    SegmentCacheHandle segment_cache;
925
3.23k
    RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
926
3.23k
            std::static_pointer_cast<BetaRowset>(rs), &segment_cache));
927
928
14.4k
    for (const auto& column : rs->tablet_schema()->columns()) {
929
14.4k
        if (!column->is_variant_type() || column->unique_id() < 0) {
930
9.29k
            continue;
931
9.29k
        }
932
5.12k
        if (!should_check_variant_path_stats(*column)) {
933
0
            continue;
934
0
        }
935
5.12k
        for (const auto& segment : segment_cache.get_segments()) {
936
2.09k
            std::shared_ptr<ColumnReader> column_reader;
937
2.09k
            OlapReaderStatistics stats;
938
2.09k
            RETURN_IF_ERROR(
939
2.09k
                    segment->get_column_reader(column->unique_id(), &column_reader, &stats));
940
2.09k
            if (!column_reader) {
941
0
                continue;
942
0
            }
943
944
2.09k
            CHECK(column_reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT);
945
2.09k
            auto* variant_column_reader =
946
2.09k
                    assert_cast<segment_v2::VariantColumnReader*>(column_reader.get());
947
            // load external meta before getting stats
948
2.09k
            RETURN_IF_ERROR(variant_column_reader->load_external_meta_once());
949
2.09k
            const auto* source_stats = variant_column_reader->get_stats();
950
2.09k
            CHECK(source_stats);
951
952
            // agg path -> stats
953
9.55k
            for (const auto& [path, size] : source_stats->sparse_column_non_null_size) {
954
9.55k
                (*uid_to_path_stats)[column->unique_id()][path] += size;
955
9.55k
            }
956
957
4.50k
            for (const auto& [path, size] : source_stats->subcolumns_non_null_size) {
958
4.50k
                (*uid_to_path_stats)[column->unique_id()][path] += size;
959
4.50k
            }
960
2.09k
        }
961
5.12k
    }
962
3.23k
    return Status::OK();
963
3.23k
}
964
965
Status VariantCompactionUtil::aggregate_variant_extended_info(
966
        const RowsetSharedPtr& rs,
967
5.13k
        std::unordered_map<int32_t, VariantExtendedInfo>* uid_to_variant_extended_info) {
968
5.13k
    SegmentCacheHandle segment_cache;
969
5.13k
    RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
970
5.13k
            std::static_pointer_cast<BetaRowset>(rs), &segment_cache));
971
972
22.7k
    for (const auto& column : rs->tablet_schema()->columns()) {
973
22.7k
        if (!column->is_variant_type()) {
974
15.9k
            continue;
975
15.9k
        }
976
6.86k
        auto& extended_info = (*uid_to_variant_extended_info)[column->unique_id()];
977
6.86k
        if (column->variant_enable_nested_group()) {
978
0
            extended_info.has_nested_group = true;
979
0
        }
980
6.86k
        for (const auto& segment : segment_cache.get_segments()) {
981
3.56k
            std::shared_ptr<ColumnReader> column_reader;
982
3.56k
            OlapReaderStatistics stats;
983
3.56k
            RETURN_IF_ERROR(
984
3.56k
                    segment->get_column_reader(column->unique_id(), &column_reader, &stats));
985
3.56k
            if (!column_reader) {
986
0
                continue;
987
0
            }
988
989
3.56k
            CHECK(column_reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT);
990
3.56k
            auto* variant_column_reader =
991
3.56k
                    assert_cast<segment_v2::VariantColumnReader*>(column_reader.get());
992
            // load external meta before getting stats
993
3.56k
            RETURN_IF_ERROR(variant_column_reader->load_external_meta_once());
994
3.56k
            const auto* source_stats = variant_column_reader->get_stats();
995
3.56k
            CHECK(source_stats);
996
997
3.56k
            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.04k
                for (const auto& [path, size] : source_stats->sparse_column_non_null_size) {
1001
5.04k
                    extended_info.path_to_none_null_values[path] += size;
1002
5.04k
                    extended_info.sparse_paths.emplace(path);
1003
5.04k
                }
1004
1005
5.39k
                for (const auto& [path, size] : source_stats->subcolumns_non_null_size) {
1006
5.39k
                    extended_info.path_to_none_null_values[path] += size;
1007
5.39k
                }
1008
3.56k
            }
1009
1010
            //2. agg path -> schema
1011
3.56k
            variant_column_reader->get_subcolumns_types(&extended_info.path_to_data_types);
1012
1013
            // 3. extract typed paths
1014
3.56k
            variant_column_reader->get_typed_paths(&extended_info.typed_paths);
1015
1016
            // 4. extract nested paths
1017
3.56k
            if (!column->variant_enable_nested_group()) {
1018
3.56k
                variant_column_reader->get_nested_paths(&extended_info.nested_paths);
1019
3.56k
            }
1020
3.56k
        }
1021
6.86k
    }
1022
5.13k
    return Status::OK();
1023
5.13k
}
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
694
                                         TabletSchema::PathsSetInfo& paths_set_info) {
1029
    // max_subcolumns_count is 0 means no limit
1030
694
    if (max_subcolumns_count > 0 && stats.size() > max_subcolumns_count) {
1031
187
        std::vector<std::pair<size_t, std::string_view>> paths_with_sizes;
1032
187
        paths_with_sizes.reserve(stats.size());
1033
4.54k
        for (const auto& [path, size] : stats) {
1034
4.54k
            paths_with_sizes.emplace_back(size, path);
1035
4.54k
        }
1036
187
        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
4.54k
        for (const auto& [size, path] : paths_with_sizes) {
1040
4.54k
            if (paths_set_info.sub_path_set.size() < max_subcolumns_count) {
1041
501
                paths_set_info.sub_path_set.emplace(path);
1042
4.03k
            } else {
1043
4.03k
                paths_set_info.sparse_path_set.emplace(path);
1044
4.03k
            }
1045
4.54k
        }
1046
187
        LOG(INFO) << "subpaths " << paths_set_info.sub_path_set.size() << " sparse paths "
1047
187
                  << paths_set_info.sparse_path_set.size() << " variant max subcolumns count "
1048
187
                  << max_subcolumns_count << " stats size " << paths_with_sizes.size();
1049
507
    } else {
1050
        // Apply all paths as subcolumns
1051
720
        for (const auto& [path, _] : stats) {
1052
720
            paths_set_info.sub_path_set.emplace(path);
1053
720
        }
1054
507
    }
1055
694
}
1056
1057
Status VariantCompactionUtil::check_path_stats(const std::vector<RowsetSharedPtr>& intputs,
1058
11.9k
                                               RowsetSharedPtr output, BaseTabletSPtr tablet) {
1059
11.9k
    if (output->tablet_schema()->num_variant_columns() == 0) {
1060
11.2k
        return Status::OK();
1061
11.2k
    }
1062
5.07k
    for (const auto& rowset : intputs) {
1063
23.8k
        for (const auto& column : rowset->tablet_schema()->columns()) {
1064
23.8k
            if (column->is_variant_type() && !should_check_variant_path_stats(*column)) {
1065
0
                return Status::OK();
1066
0
            }
1067
23.8k
        }
1068
5.07k
    }
1069
    // check no extended schema in input rowsets
1070
5.08k
    for (const auto& rowset : intputs) {
1071
23.7k
        for (const auto& column : rowset->tablet_schema()->columns()) {
1072
23.7k
            if (column->is_extracted_column()) {
1073
0
                return Status::OK();
1074
0
            }
1075
23.7k
        }
1076
5.08k
    }
1077
621
#ifndef BE_TEST
1078
    // check no extended schema in output rowset
1079
2.92k
    for (const auto& column : output->tablet_schema()->columns()) {
1080
2.92k
        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.92k
    }
1091
621
#endif
1092
    // only check path stats for dup_keys since the rows may be merged in other models
1093
621
    if (tablet->keys_type() != KeysType::DUP_KEYS) {
1094
220
        return Status::OK();
1095
220
    }
1096
    // if there is a delete predicate in the input rowsets, we skip the path stats check
1097
2.76k
    for (auto& rowset : intputs) {
1098
2.76k
        if (rowset->rowset_meta()->has_delete_predicate()) {
1099
4
            return Status::OK();
1100
4
        }
1101
2.76k
    }
1102
1.82k
    for (const auto& column : output->tablet_schema()->columns()) {
1103
1.82k
        if (column->is_variant_type() && !should_check_variant_path_stats(*column)) {
1104
0
            return Status::OK();
1105
0
        }
1106
1.82k
    }
1107
397
    std::unordered_map<int32_t, PathToNoneNullValues> original_uid_to_path_stats;
1108
2.74k
    for (const auto& rs : intputs) {
1109
2.74k
        RETURN_IF_ERROR(aggregate_path_to_stats(rs, &original_uid_to_path_stats));
1110
2.74k
    }
1111
397
    std::unordered_map<int32_t, PathToNoneNullValues> output_uid_to_path_stats;
1112
397
    RETURN_IF_ERROR(aggregate_path_to_stats(output, &output_uid_to_path_stats));
1113
397
    for (const auto& [uid, stats] : output_uid_to_path_stats) {
1114
254
        if (output->tablet_schema()->column_by_uid(uid).is_variant_type() &&
1115
254
            output->tablet_schema()->column_by_uid(uid).variant_enable_doc_mode()) {
1116
41
            continue;
1117
41
        }
1118
213
        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
213
        if (stats.size() > output->tablet_schema()
1126
213
                                   ->column_by_uid(uid)
1127
213
                                   .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
212
        else {
1149
4.44k
            for (const auto& [path, size] : stats) {
1150
4.44k
                if (original_uid_to_path_stats.at(uid).find(path) ==
1151
4.44k
                    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
4.44k
                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
4.44k
            }
1165
212
        }
1166
213
    }
1167
1168
397
    return Status::OK();
1169
397
}
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
680
        TabletSchema::PathsSetInfo& paths_set_info) {
1175
680
    if (parent_column->variant_enable_typed_paths_to_sparse()) {
1176
40
        return Status::OK();
1177
40
    }
1178
640
    for (const auto& path : typed_paths) {
1179
467
        TabletSchema::SubColumnInfo sub_column_info;
1180
467
        if (generate_sub_column_info(*target, parent_column->unique_id(), path, &sub_column_info)) {
1181
466
            inherit_column_attributes(*parent_column, sub_column_info.column);
1182
466
            output_schema->append_column(sub_column_info.column);
1183
466
            paths_set_info.typed_path_set.insert({path, std::move(sub_column_info)});
1184
466
            VLOG_DEBUG << "append typed column " << path;
1185
466
        } else {
1186
1
            return Status::InternalError("Failed to generate sub column info for path {}", path);
1187
1
        }
1188
467
    }
1189
639
    return Status::OK();
1190
640
}
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
684
        TabletSchemaSPtr& output_schema, TabletSchema::PathsSetInfo& paths_set_info) {
1196
684
    const auto& parent_indexes = output_schema->inverted_indexs(parent_column->unique_id());
1197
684
    for (const auto& path : nested_paths) {
1198
8
        const auto& find_data_types = path_to_data_types.find(path);
1199
8
        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
7
        DataTypePtr data_type;
1203
7
        get_least_supertype_jsonb(find_data_types->second, &data_type);
1204
1205
7
        const std::string& column_name = parent_column->name_lower_case() + "." + path.get_path();
1206
7
        PathInDataBuilder full_path_builder;
1207
7
        auto full_path = full_path_builder.append(parent_column->name_lower_case(), false)
1208
7
                                 .append(path.get_parts(), false)
1209
7
                                 .build();
1210
7
        TabletColumn nested_column =
1211
7
                get_column_by_type(data_type, column_name,
1212
7
                                   ExtraInfo {.unique_id = -1,
1213
7
                                              .parent_unique_id = parent_column->unique_id(),
1214
7
                                              .path_info = full_path});
1215
7
        inherit_column_attributes(*parent_column, nested_column);
1216
7
        TabletIndexes sub_column_indexes;
1217
7
        inherit_index(parent_indexes, sub_column_indexes, nested_column);
1218
7
        paths_set_info.subcolumn_indexes.emplace(path.get_path(), std::move(sub_column_indexes));
1219
7
        output_schema->append_column(nested_column);
1220
7
        VLOG_DEBUG << "append nested column " << path.get_path();
1221
7
    }
1222
683
    return Status::OK();
1223
684
}
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
676
        const std::unordered_set<std::string>& sparse_paths, TabletSchemaSPtr& output_schema) {
1229
676
    auto& path_set = paths_set_info.sub_path_set;
1230
676
    std::vector<StringRef> sorted_subpaths(path_set.begin(), path_set.end());
1231
676
    std::sort(sorted_subpaths.begin(), sorted_subpaths.end());
1232
676
    const auto& parent_indexes = target->inverted_indexs(parent_column->unique_id());
1233
    // append subcolumns
1234
1.17k
    for (const auto& subpath : sorted_subpaths) {
1235
1.17k
        auto column_name = parent_column->name_lower_case() + "." + subpath.to_string();
1236
1.17k
        auto column_path = make_full_subcolumn_path(parent_column,
1237
1.17k
                                                    std::string_view(subpath.data, subpath.size));
1238
1239
1.17k
        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.17k
        TabletSchema::SubColumnInfo sub_column_info;
1246
1.17k
        if (parent_column->variant_enable_typed_paths_to_sparse() &&
1247
1.17k
            generate_sub_column_info(*target, parent_column->unique_id(), std::string(subpath),
1248
72
                                     &sub_column_info)) {
1249
62
            inherit_column_attributes(*parent_column, sub_column_info.column);
1250
62
            output_schema->append_column(sub_column_info.column);
1251
62
            paths_set_info.subcolumn_indexes.emplace(subpath, std::move(sub_column_info.indexes));
1252
62
            VLOG_DEBUG << "append typed column " << subpath;
1253
1.10k
        } else if (find_data_types == path_to_data_types.end() || find_data_types->second.empty() ||
1254
1.10k
                   sparse_paths.find(std::string(subpath)) != sparse_paths.end() ||
1255
1.10k
                   sparse_paths.size() >=
1256
976
                           parent_column->variant_max_sparse_column_statistics_size()) {
1257
139
            TabletColumn subcolumn;
1258
139
            subcolumn.set_name(column_name);
1259
139
            subcolumn.set_type(FieldType::OLAP_FIELD_TYPE_VARIANT);
1260
139
            subcolumn.set_parent_unique_id(parent_column->unique_id());
1261
139
            subcolumn.set_path_info(column_path);
1262
139
            subcolumn.set_aggregation_method(parent_column->aggregation());
1263
139
            subcolumn.set_variant_max_subcolumns_count(
1264
139
                    parent_column->variant_max_subcolumns_count());
1265
139
            subcolumn.set_variant_enable_doc_mode(parent_column->variant_enable_doc_mode());
1266
139
            subcolumn.set_is_nullable(true);
1267
139
            output_schema->append_column(subcolumn);
1268
139
            VLOG_DEBUG << "append sub column " << subpath << " data type "
1269
0
                       << "VARIANT";
1270
139
        }
1271
        // normal case: the subcolumn type can be calculated from the data types in segments
1272
969
        else {
1273
969
            DataTypePtr data_type;
1274
969
            get_least_supertype_jsonb(find_data_types->second, &data_type);
1275
969
            TabletColumn sub_column =
1276
969
                    get_column_by_type(data_type, column_name,
1277
969
                                       ExtraInfo {.unique_id = -1,
1278
969
                                                  .parent_unique_id = parent_column->unique_id(),
1279
969
                                                  .path_info = column_path});
1280
969
            inherit_column_attributes(*parent_column, sub_column);
1281
969
            TabletIndexes sub_column_indexes;
1282
969
            inherit_index(parent_indexes, sub_column_indexes, sub_column);
1283
969
            paths_set_info.subcolumn_indexes.emplace(subpath, std::move(sub_column_indexes));
1284
969
            output_schema->append_column(sub_column);
1285
969
            VLOG_DEBUG << "append sub column " << subpath << " data type " << data_type->get_name();
1286
969
        }
1287
1.17k
    }
1288
676
}
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
15
        TabletSchemaSPtr& output_schema) {
1294
15
    const auto& parent_indexes = target->inverted_indexs(parent_column->unique_id());
1295
61
    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
61
        if (data_types.empty() || path.empty() || path.get_is_typed() || path.has_nested_part()) {
1299
13
            continue;
1300
13
        }
1301
48
        DataTypePtr data_type;
1302
48
        get_least_supertype_jsonb(data_types, &data_type);
1303
48
        auto column_name = parent_column->name_lower_case() + "." + path.get_path();
1304
48
        auto column_path = make_full_subcolumn_path(parent_column, path.get_path());
1305
48
        TabletColumn sub_column =
1306
48
                get_column_by_type(data_type, column_name,
1307
48
                                   ExtraInfo {.unique_id = -1,
1308
48
                                              .parent_unique_id = parent_column->unique_id(),
1309
48
                                              .path_info = column_path});
1310
48
        inherit_column_attributes(*parent_column, sub_column);
1311
48
        TabletIndexes sub_column_indexes;
1312
48
        inherit_index(parent_indexes, sub_column_indexes, sub_column);
1313
48
        paths_set_info.sub_path_set.emplace(path.get_path());
1314
48
        paths_set_info.subcolumn_indexes.emplace(path.get_path(), std::move(sub_column_indexes));
1315
48
        output_schema->append_column(sub_column);
1316
48
        VLOG_DEBUG << "append sub column " << path.get_path() << " data type "
1317
0
                   << data_type->get_name();
1318
48
    }
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
15
    append_empty_key_subcolumn_from_stats(paths_set_info, parent_column, output_schema);
1323
15
}
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.4k
        const std::vector<RowsetSharedPtr>& rowsets, TabletSchemaSPtr& target) {
1332
11.4k
    std::unordered_map<int32_t, VariantExtendedInfo> uid_to_variant_extended_info;
1333
11.4k
    const bool needs_variant_extended_info =
1334
112k
            std::ranges::any_of(target->columns(), [](const TabletColumnPtr& column) {
1335
112k
                return column->is_variant_type() && (should_check_variant_path_stats(*column) ||
1336
627
                                                     column->variant_enable_nested_group());
1337
112k
            });
1338
11.4k
    if (needs_variant_extended_info) {
1339
        // collect path stats from all rowsets and segments
1340
5.13k
        for (const auto& rs : rowsets) {
1341
5.13k
            RETURN_IF_ERROR(aggregate_variant_extended_info(rs, &uid_to_variant_extended_info));
1342
5.13k
        }
1343
627
    }
1344
1345
    // build the output schema
1346
11.4k
    TabletSchemaSPtr output_schema = std::make_shared<TabletSchema>();
1347
11.4k
    output_schema->shawdow_copy_without_columns(*target);
1348
11.4k
    std::unordered_map<int32_t, TabletSchema::PathsSetInfo> uid_to_paths_set_info;
1349
11.4k
    const auto ng_root_uids =
1350
11.4k
            collect_nested_group_compaction_root_uids(target, uid_to_variant_extended_info);
1351
116k
    for (const TabletColumnPtr& column : target->columns()) {
1352
116k
        if (!column->is_extracted_column()) {
1353
116k
            output_schema->append_column(*column);
1354
116k
        }
1355
116k
        if (!column->is_variant_type()) {
1356
115k
            continue;
1357
115k
        }
1358
18.4E
        VLOG_DEBUG << "column " << column->name() << " unique id " << column->unique_id();
1359
1360
755
        const auto info_it = uid_to_variant_extended_info.find(column->unique_id());
1361
755
        const VariantExtendedInfo empty_extended_info;
1362
755
        const VariantExtendedInfo& extended_info = info_it == uid_to_variant_extended_info.end()
1363
755
                                                           ? empty_extended_info
1364
755
                                                           : info_it->second;
1365
755
        auto& paths_set_info = uid_to_paths_set_info[column->unique_id()];
1366
755
        const bool use_nested_group_compaction_schema = ng_root_uids.contains(column->unique_id());
1367
1368
755
        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
754
        if (column->variant_enable_doc_mode()) {
1388
189
            const int bucket_num = std::max(1, column->variant_doc_hash_shard_count());
1389
551
            for (int b = 0; b < bucket_num; ++b) {
1390
362
                TabletColumn doc_value_bucket_column = create_doc_value_column(*column, b);
1391
362
                doc_value_bucket_column.set_type(FieldType::OLAP_FIELD_TYPE_VARIANT);
1392
362
                doc_value_bucket_column.set_is_nullable(false);
1393
362
                doc_value_bucket_column.set_variant_enable_doc_mode(true);
1394
362
                output_schema->append_column(doc_value_bucket_column);
1395
362
            }
1396
189
            continue;
1397
189
        }
1398
1399
        // 1. append typed columns
1400
565
        RETURN_IF_ERROR(get_compaction_typed_columns(target, extended_info.typed_paths, column,
1401
565
                                                     output_schema, paths_set_info));
1402
1403
        // 2. append nested columns
1404
565
        RETURN_IF_ERROR(get_compaction_nested_columns(extended_info.nested_paths,
1405
565
                                                      extended_info.path_to_data_types, column,
1406
565
                                                      output_schema, paths_set_info));
1407
1408
        // 3. get the subpaths
1409
565
        get_subpaths(column->variant_max_subcolumns_count(), extended_info.path_to_none_null_values,
1410
565
                     paths_set_info);
1411
1412
        // 4. append subcolumns
1413
669
        if (column->variant_max_subcolumns_count() > 0 || !column->get_sub_columns().empty()) {
1414
669
            get_compaction_subcolumns_from_subpaths(paths_set_info, column, target,
1415
669
                                                    extended_info.path_to_data_types,
1416
669
                                                    extended_info.sparse_paths, output_schema);
1417
669
        }
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
565
        int bucket_num = std::max(1, column->variant_sparse_hash_shard_count());
1430
573
        if (bucket_num > 1) {
1431
3.23k
            for (int b = 0; b < bucket_num; ++b) {
1432
2.66k
                TabletColumn sparse_bucket_column = create_sparse_shard_column(*column, b);
1433
2.66k
                output_schema->append_column(sparse_bucket_column);
1434
2.66k
            }
1435
18.4E
        } else {
1436
18.4E
            TabletColumn sparse_column = create_sparse_column(*column);
1437
18.4E
            output_schema->append_column(sparse_column);
1438
18.4E
        }
1439
565
    }
1440
1441
11.4k
    target = output_schema;
1442
    // used to merge & filter path to sparse column during reading in compaction
1443
11.4k
    target->set_path_set_info(std::move(uid_to_paths_set_info));
1444
18.4E
    VLOG_DEBUG << "dump schema " << target->dump_full_schema();
1445
11.4k
    return Status::OK();
1446
11.4k
}
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.91k
                                                    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.91k
    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.91k
    const auto& sparse_data_paths =
1458
1.91k
            assert_cast<const ColumnString*>(map_column.get_keys_ptr().get());
1459
1.91k
    const auto& serialized_sparse_column_offsets = map_column.get_offsets();
1460
1.91k
    auto& count_map = *stats->mutable_sparse_column_non_null_size();
1461
    // Iterate through all paths in the sparse column
1462
614k
    for (size_t i = row_pos; i != row_pos + num_rows; ++i) {
1463
612k
        size_t offset = serialized_sparse_column_offsets[i - 1];
1464
612k
        size_t end = serialized_sparse_column_offsets[i];
1465
1.96M
        for (size_t j = offset; j != end; ++j) {
1466
1.35M
            auto path = sparse_data_paths->get_data_at(j);
1467
1468
1.35M
            const auto& sparse_path = path.to_string();
1469
            // If path already exists in statistics, increment its count
1470
1.35M
            if (auto it = count_map.find(sparse_path); it != count_map.end()) {
1471
1.35M
                ++it->second;
1472
1.35M
            }
1473
            // If path doesn't exist and we haven't hit the max statistics size limit,
1474
            // add it with count 1
1475
3.99k
            else if (count_map.size() < max_sparse_column_statistics_size) {
1476
3.98k
                count_map.emplace(sparse_path, 1);
1477
3.98k
            }
1478
1.35M
        }
1479
612k
    }
1480
1481
1.91k
    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.91k
}
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
24.6M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
24.6M
        if constexpr (T == TYPE_ARRAY) {
1497
2.54M
            const size_t size = x.size();
1498
2.54M
            size_t dimensions = 0;
1499
6.26M
            for (size_t i = 0; i < size; ++i) {
1500
3.71M
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
3.71M
                dimensions = std::max(dimensions, element_dimensions);
1502
3.71M
            }
1503
2.54M
            return 1 + dimensions;
1504
22.1M
        } else {
1505
22.1M
            return 0;
1506
22.1M
        }
1507
24.6M
    }
_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
479
    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
479
        } else {
1505
479
            return 0;
1506
479
        }
1507
479
    }
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
395
    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
395
        } else {
1505
395
            return 0;
1506
395
        }
1507
395
    }
_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.01k
    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.01k
        } else {
1505
1.01k
            return 0;
1506
1.01k
        }
1507
1.01k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE4EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
1.00k
    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.00k
        } else {
1505
1.00k
            return 0;
1506
1.00k
        }
1507
1.00k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE5EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
2.19k
    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.19k
        } else {
1505
2.19k
            return 0;
1506
2.19k
        }
1507
2.19k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE6EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
6.64M
    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
6.64M
        } else {
1505
6.64M
            return 0;
1506
6.64M
        }
1507
6.64M
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE38EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE39EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE8EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
858
    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
858
        } else {
1505
858
            return 0;
1506
858
        }
1507
858
    }
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
305
    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
305
        } else {
1505
305
            return 0;
1506
305
        }
1507
305
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE37EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
274
    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
274
        } else {
1505
274
            return 0;
1506
274
        }
1507
274
    }
_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
2.54M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
2.54M
        if constexpr (T == TYPE_ARRAY) {
1497
2.54M
            const size_t size = x.size();
1498
2.54M
            size_t dimensions = 0;
1499
6.26M
            for (size_t i = 0; i < size; ++i) {
1500
3.71M
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
3.71M
                dimensions = std::max(dimensions, element_dimensions);
1502
3.71M
            }
1503
2.54M
            return 1 + dimensions;
1504
        } else {
1505
            return 0;
1506
        }
1507
2.54M
    }
_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
755
    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
755
        } else {
1505
755
            return 0;
1506
755
        }
1507
755
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE29EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
695
    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
695
        } else {
1505
695
            return 0;
1506
695
        }
1507
695
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE20EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE30EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
70.7k
    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
70.7k
        } else {
1505
70.7k
            return 0;
1506
70.7k
        }
1507
70.7k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE35EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
557
    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
557
        } else {
1505
557
            return 0;
1506
557
        }
1507
557
    }
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.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
46.9k
        } else {
1505
46.9k
            return 0;
1506
46.9k
        }
1507
46.9k
    }
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
5.58M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
5.58M
        if constexpr (T == TYPE_ARRAY) {
1545
2.54M
            size_t size = x.size();
1546
6.26M
            for (size_t i = 0; i < size; ++i) {
1547
3.71M
                apply_visitor(*this, x[i]);
1548
3.71M
            }
1549
2.54M
            return 0;
1550
2.54M
        } else if constexpr (T == TYPE_NULL) {
1551
12.2k
            have_nulls = true;
1552
12.2k
            return 0;
1553
3.02M
        } else {
1554
3.02M
            field_types.insert(T);
1555
3.02M
            type_indexes.insert(T);
1556
3.02M
            return 0;
1557
3.02M
        }
1558
5.58M
    }
_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
479
    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
479
        } else {
1554
479
            field_types.insert(T);
1555
479
            type_indexes.insert(T);
1556
479
            return 0;
1557
479
        }
1558
479
    }
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
395
    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
395
        } else {
1554
395
            field_types.insert(T);
1555
395
            type_indexes.insert(T);
1556
395
            return 0;
1557
395
        }
1558
395
    }
_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.01k
    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.01k
        } else {
1554
1.01k
            field_types.insert(T);
1555
1.01k
            type_indexes.insert(T);
1556
1.01k
            return 0;
1557
1.01k
        }
1558
1.01k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE4EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
1.00k
    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.00k
        } else {
1554
1.00k
            field_types.insert(T);
1555
1.00k
            type_indexes.insert(T);
1556
1.00k
            return 0;
1557
1.00k
        }
1558
1.00k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE5EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
1.51k
    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.51k
        } else {
1554
1.51k
            field_types.insert(T);
1555
1.51k
            type_indexes.insert(T);
1556
1.51k
            return 0;
1557
1.51k
        }
1558
1.51k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE6EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
1.51M
    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.51M
        } else {
1554
1.51M
            field_types.insert(T);
1555
1.51M
            type_indexes.insert(T);
1556
1.51M
            return 0;
1557
1.51M
        }
1558
1.51M
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE38EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE39EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE8EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
857
    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
857
        } else {
1554
857
            field_types.insert(T);
1555
857
            type_indexes.insert(T);
1556
857
            return 0;
1557
857
        }
1558
857
    }
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
305
    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
305
        } else {
1554
305
            field_types.insert(T);
1555
305
            type_indexes.insert(T);
1556
305
            return 0;
1557
305
        }
1558
305
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE37EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
274
    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
274
        } else {
1554
274
            field_types.insert(T);
1555
274
            type_indexes.insert(T);
1556
274
            return 0;
1557
274
        }
1558
274
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE23EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
1.15M
    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.15M
        } else {
1554
1.15M
            field_types.insert(T);
1555
1.15M
            type_indexes.insert(T);
1556
1.15M
            return 0;
1557
1.15M
        }
1558
1.15M
    }
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
2.54M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
2.54M
        if constexpr (T == TYPE_ARRAY) {
1545
2.54M
            size_t size = x.size();
1546
6.26M
            for (size_t i = 0; i < size; ++i) {
1547
3.71M
                apply_visitor(*this, x[i]);
1548
3.71M
            }
1549
2.54M
            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
2.54M
    }
_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
755
    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
755
        } else {
1554
755
            field_types.insert(T);
1555
755
            type_indexes.insert(T);
1556
755
            return 0;
1557
755
        }
1558
755
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE29EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
695
    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
695
        } else {
1554
695
            field_types.insert(T);
1555
695
            type_indexes.insert(T);
1556
695
            return 0;
1557
695
        }
1558
695
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE20EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE30EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
70.7k
    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
70.7k
        } else {
1554
70.7k
            field_types.insert(T);
1555
70.7k
            type_indexes.insert(T);
1556
70.7k
            return 0;
1557
70.7k
        }
1558
70.7k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE35EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
557
    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
557
        } else {
1554
557
            field_types.insert(T);
1555
557
            type_indexes.insert(T);
1556
557
            return 0;
1557
557
        }
1558
557
    }
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
44
    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
44
        } else {
1554
44
            field_types.insert(T);
1555
44
            type_indexes.insert(T);
1556
44
            return 0;
1557
44
        }
1558
44
    }
1559
1.86M
    void get_scalar_type(PrimitiveType* type) const {
1560
1.86M
        if (type_indexes.size() == 1) {
1561
            // Most cases will have only one type
1562
1.77M
            *type = *type_indexes.begin();
1563
1.77M
            return;
1564
1.77M
        }
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.86M
    bool contain_nulls() const { return have_nulls; }
1570
1.86M
    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.9M
void get_field_info_impl(const Field& field, FieldInfo* info) {
1580
20.9M
    Visitor to_scalar_type_visitor;
1581
20.9M
    apply_visitor(to_scalar_type_visitor, field);
1582
20.9M
    PrimitiveType type_id;
1583
20.9M
    to_scalar_type_visitor.get_scalar_type(&type_id);
1584
    // array item's dimension may missmatch, eg. [1, 2, [1, 2, 3]]
1585
20.9M
    *info = {type_id, to_scalar_type_visitor.contain_nulls(),
1586
20.9M
             to_scalar_type_visitor.need_convert_field(),
1587
20.9M
             apply_visitor(FieldVisitorToNumberOfDimensions(), field)};
1588
20.9M
}
_ZN5doris12variant_util19get_field_info_implINS0_24FieldVisitorToScalarTypeEEEvRKNS_5FieldEPNS_9FieldInfoE
Line
Count
Source
1579
1.86M
void get_field_info_impl(const Field& field, FieldInfo* info) {
1580
1.86M
    Visitor to_scalar_type_visitor;
1581
1.86M
    apply_visitor(to_scalar_type_visitor, field);
1582
1.86M
    PrimitiveType type_id;
1583
1.86M
    to_scalar_type_visitor.get_scalar_type(&type_id);
1584
    // array item's dimension may missmatch, eg. [1, 2, [1, 2, 3]]
1585
1.86M
    *info = {type_id, to_scalar_type_visitor.contain_nulls(),
1586
1.86M
             to_scalar_type_visitor.need_convert_field(),
1587
1.86M
             apply_visitor(FieldVisitorToNumberOfDimensions(), field)};
1588
1.86M
}
_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.9M
void get_field_info(const Field& field, FieldInfo* info) {
1591
20.9M
    if (field.is_complex_field()) {
1592
1.86M
        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.9M
}
1597
1598
bool generate_sub_column_info(const TabletSchema& schema, int32_t col_unique_id,
1599
                              const std::string& path,
1600
223k
                              TabletSchema::SubColumnInfo* sub_column_info) {
1601
223k
    const auto& parent_column = schema.column_by_uid(col_unique_id);
1602
223k
    std::function<void(const TabletColumn&, TabletColumn*)> generate_result_column =
1603
223k
            [&](const TabletColumn& from_column, TabletColumn* to_column) {
1604
15.1k
                to_column->set_name(parent_column.name_lower_case() + "." + path);
1605
15.1k
                to_column->set_type(from_column.type());
1606
15.1k
                to_column->set_parent_unique_id(parent_column.unique_id());
1607
15.1k
                bool is_typed = !parent_column.variant_enable_typed_paths_to_sparse();
1608
15.1k
                to_column->set_path_info(
1609
15.1k
                        PathInData(parent_column.name_lower_case() + "." + path, is_typed));
1610
15.1k
                to_column->set_aggregation_method(parent_column.aggregation());
1611
15.1k
                to_column->set_is_nullable(true);
1612
15.1k
                to_column->set_parent_unique_id(parent_column.unique_id());
1613
15.1k
                if (from_column.is_decimal()) {
1614
14.8k
                    to_column->set_precision(from_column.precision());
1615
14.8k
                }
1616
15.1k
                to_column->set_frac(from_column.frac());
1617
1618
15.1k
                if (from_column.is_array_type()) {
1619
2.48k
                    TabletColumn nested_column;
1620
2.48k
                    generate_result_column(*from_column.get_sub_columns()[0], &nested_column);
1621
2.48k
                    to_column->add_sub_column(nested_column);
1622
2.48k
                }
1623
15.1k
            };
1624
1625
223k
    auto generate_index = [&](const std::string& pattern) {
1626
        // 1. find subcolumn's index
1627
12.6k
        if (const auto& indexes = schema.inverted_index_by_field_pattern(col_unique_id, pattern);
1628
12.6k
            !indexes.empty()) {
1629
4.83k
            for (const auto& index : indexes) {
1630
4.83k
                auto index_ptr = std::make_shared<TabletIndex>(*index);
1631
4.83k
                index_ptr->set_escaped_escaped_index_suffix_path(
1632
4.83k
                        sub_column_info->column.path_info_ptr()->get_path());
1633
4.83k
                sub_column_info->indexes.emplace_back(std::move(index_ptr));
1634
4.83k
            }
1635
4.73k
        }
1636
        // 2. find parent column's index
1637
7.89k
        else if (const auto parent_index = schema.inverted_indexs(col_unique_id);
1638
7.89k
                 !parent_index.empty()) {
1639
408
            inherit_index(parent_index, sub_column_info->indexes, sub_column_info->column);
1640
7.48k
        } else {
1641
7.48k
            sub_column_info->indexes.clear();
1642
7.48k
        }
1643
12.6k
    };
1644
1645
223k
    const auto& sub_columns = parent_column.get_sub_columns();
1646
223k
    for (const auto& sub_column : sub_columns) {
1647
217k
        const char* pattern = sub_column->name().c_str();
1648
217k
        switch (sub_column->pattern_type()) {
1649
5.24k
        case PatternTypePB::MATCH_NAME: {
1650
5.24k
            if (strcmp(pattern, path.c_str()) == 0) {
1651
936
                generate_result_column(*sub_column, &sub_column_info->column);
1652
936
                generate_index(sub_column->name());
1653
936
                return true;
1654
936
            }
1655
4.31k
            break;
1656
5.24k
        }
1657
212k
        case PatternTypePB::MATCH_NAME_GLOB: {
1658
212k
            if (glob_match_re2(pattern, path)) {
1659
11.6k
                generate_result_column(*sub_column, &sub_column_info->column);
1660
11.6k
                generate_index(sub_column->name());
1661
11.6k
                return true;
1662
11.6k
            }
1663
200k
            break;
1664
212k
        }
1665
200k
        default:
1666
0
            break;
1667
217k
        }
1668
217k
    }
1669
210k
    return false;
1670
223k
}
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
85.6k
                   const std::string& suffix_path, bool is_array_nested_type) {
1752
85.6k
    if (parent_indexes.empty()) {
1753
75.2k
        return false;
1754
75.2k
    }
1755
10.3k
    subcolumns_indexes.clear();
1756
    // bkd index or array index only need to inherit one index
1757
10.3k
    if (field_is_numeric_type(column_type) ||
1758
10.3k
        (is_array_nested_type &&
1759
7.46k
         (field_is_numeric_type(column_type) || field_is_slice_type(column_type)))) {
1760
2.95k
        auto index_ptr = std::make_shared<TabletIndex>(*parent_indexes[0]);
1761
2.95k
        index_ptr->set_escaped_escaped_index_suffix_path(suffix_path);
1762
        // no need parse for bkd index or array index
1763
2.95k
        index_ptr->remove_parser_and_analyzer();
1764
2.95k
        subcolumns_indexes.emplace_back(std::move(index_ptr));
1765
2.95k
        return true;
1766
2.95k
    }
1767
    // string type need to inherit all indexes
1768
7.42k
    else if (field_is_slice_type(column_type) && !is_array_nested_type) {
1769
7.41k
        for (const auto& index : parent_indexes) {
1770
7.41k
            auto index_ptr = std::make_shared<TabletIndex>(*index);
1771
7.41k
            index_ptr->set_escaped_escaped_index_suffix_path(suffix_path);
1772
7.41k
            subcolumns_indexes.emplace_back(std::move(index_ptr));
1773
7.41k
        }
1774
7.38k
        return true;
1775
7.38k
    }
1776
40
    return false;
1777
10.3k
}
1778
1779
bool inherit_index(const std::vector<const TabletIndex*>& parent_indexes,
1780
85.7k
                   TabletIndexes& subcolumns_indexes, const TabletColumn& column) {
1781
85.7k
    if (!column.is_extracted_column()) {
1782
3
        return false;
1783
3
    }
1784
85.7k
    if (column.is_array_type()) {
1785
3.16k
        if (column.get_sub_columns().empty()) {
1786
0
            return false;
1787
0
        }
1788
3.16k
        const TabletColumn* nested = column.get_sub_columns()[0].get();
1789
3.16k
        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
3.16k
        if (nested == nullptr) {
1796
0
            return false;
1797
0
        }
1798
3.16k
        return inherit_index(parent_indexes, subcolumns_indexes, nested->type(),
1799
3.16k
                             column.path_info_ptr()->get_path(), true);
1800
3.16k
    }
1801
82.6k
    return inherit_index(parent_indexes, subcolumns_indexes, column.type(),
1802
82.6k
                         column.path_info_ptr()->get_path());
1803
85.7k
}
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
39
            return {f(), this};
1868
39
        }
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
38
            return {f(), this};
1868
38
        }
1869
4.50k
        auto object = stack.top().release();
1870
4.50k
        stack.pop();
1871
4.50k
        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.2M
static inline void append_binary_bytes(ColumnString::Chars& chars, const void* data, size_t size) {
1884
47.2M
    const auto old_size = chars.size();
1885
47.2M
    chars.resize(old_size + size);
1886
47.2M
    memcpy(chars.data() + old_size, reinterpret_cast<const char*>(data), size);
1887
47.2M
}
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
261k
    case PrimitiveType::TYPE_BOOLEAN: {
1905
261k
        append_binary_type(chars,
1906
261k
                           primitive_type_to_storage_field_type(PrimitiveType::TYPE_BOOLEAN));
1907
261k
        const auto v = static_cast<UInt8>(field.get<PrimitiveType::TYPE_BOOLEAN>());
1908
261k
        append_binary_bytes(chars, &v, sizeof(UInt8));
1909
261k
        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
530k
    case PrimitiveType::TYPE_ARRAY: {
1945
530k
        append_binary_type(chars, FieldType::OLAP_FIELD_TYPE_ARRAY);
1946
530k
        const auto& a = field.get<PrimitiveType::TYPE_ARRAY>();
1947
530k
        append_binary_sizet(chars, a.size());
1948
791k
        for (const auto& elem : a) {
1949
791k
            append_field_to_binary_chars(elem, chars);
1950
791k
        }
1951
530k
        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
914
        result = ParseResult {};
1969
914
    }
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
797
                if (!column_variant.enable_doc_mode() &&
2080
797
                    field_info.scalar_type_id == PrimitiveType::INVALID_TYPE) {
2081
3
                    continue;
2082
3
                }
2083
794
                auto* subcolumn = column_variant.get_subcolumn(paths[i]);
2084
794
                DCHECK(subcolumn != nullptr);
2085
794
                flush_defaults(subcolumn);
2086
794
                subcolumn->insert(std::move(values[i]), std::move(field_info));
2087
794
                continue;
2088
797
            }
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
72.0M
                  [&](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.37M
    doc_value_data_offsets.push_back(doc_value_data_paths->size());
2115
    // /// Insert default values to missed subcolumns.
2116
1.37M
    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.37M
    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.37M
#ifndef NDEBUG
2137
1.37M
    column_variant.check_consistency();
2138
1.37M
#endif
2139
1.37M
}
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.36k
                                              const std::vector<ParseConfig>& configs) {
2228
9.71k
    for (size_t i = 0; i < variant_pos.size(); ++i) {
2229
5.34k
        auto column_ref = block.get_by_position(variant_pos[i]).column;
2230
5.34k
        bool is_nullable = is_column_nullable(*column_ref);
2231
5.34k
        MutableColumnPtr owner_column = IColumn::mutate(std::move(column_ref));
2232
5.34k
        ColumnPtr nullable_null_map;
2233
5.34k
        MutableColumnPtr var_column;
2234
5.34k
        if (is_nullable) {
2235
4.96k
            const auto& nullable = assert_cast<const ColumnNullable&>(*owner_column);
2236
4.96k
            nullable_null_map = nullable.get_null_map_column_ptr();
2237
4.96k
            var_column = IColumn::mutate(nullable.get_nested_column_ptr());
2238
4.96k
        } else {
2239
384
            var_column = std::move(owner_column);
2240
384
        }
2241
5.34k
        auto& var = assert_cast<ColumnVariant&>(*var_column);
2242
5.34k
        var_column->finalize();
2243
2244
5.34k
        MutableColumnPtr variant_column;
2245
5.34k
        if (!var.is_scalar_variant()) {
2246
            // already parsed
2247
1.27k
            continue;
2248
1.27k
        }
2249
2250
18.4E
        VLOG_DEBUG << "parse scalar variant column: " << var.get_root_type()->get_name();
2251
4.07k
        ColumnPtr scalar_root_column;
2252
4.07k
        if (var.get_root_type()->get_primitive_type() == TYPE_JSONB) {
2253
33
            scalar_root_column = jsonb_root_to_json_string_column(*var.get_root());
2254
4.04k
        } else {
2255
4.04k
            const auto& root = *var.get_root();
2256
4.04k
            scalar_root_column =
2257
4.04k
                    is_column_nullable(root)
2258
4.04k
                            ? assert_cast<const ColumnNullable&>(root).get_nested_column_ptr()
2259
4.04k
                            : var.get_root();
2260
4.04k
        }
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.07k
        ColumnPtr result = variant_column->get_ptr();
2278
4.07k
        if (is_nullable) {
2279
4.03k
            result = ColumnNullable::create(result, nullable_null_map);
2280
4.03k
        }
2281
4.07k
        block.get_by_position(variant_pos[i]).column = result;
2282
4.07k
    }
2283
4.36k
    return Status::OK();
2284
4.36k
}
2285
2286
Status parse_and_materialize_variant_columns(Block& block, const std::vector<uint32_t>& variant_pos,
2287
4.39k
                                             const std::vector<ParseConfig>& configs) {
2288
4.39k
    RETURN_IF_CATCH_EXCEPTION(
2289
4.39k
            { return _parse_and_materialize_variant_columns(block, variant_pos, configs); });
2290
4.39k
}
2291
2292
namespace {
2293
2294
ParseConfig::ParseTo select_storage_variant_parse_target(const TabletColumn& column,
2295
5.05k
                                                         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
5.05k
    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
5.05k
    if (column.variant_enable_doc_mode()) {
2305
1.43k
        return ParseConfig::ParseTo::OnlyDocValueColumn;
2306
1.43k
    }
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.62k
    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.59k
    switch (config::variant_storage_parse_mode) {
2321
3.73k
    case 0:
2322
3.74k
    case 2:
2323
3.74k
        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.59k
    }
2331
3.59k
}
2332
2333
} // namespace
2334
2335
Status parse_and_materialize_variant_columns(Block& block, const TabletSchema& tablet_schema,
2336
4.51k
                                             const std::vector<uint32_t>& column_pos) {
2337
4.51k
    std::vector<uint32_t> variant_column_pos;
2338
4.51k
    std::vector<uint32_t> variant_schema_pos;
2339
4.51k
    variant_column_pos.reserve(column_pos.size());
2340
4.51k
    variant_schema_pos.reserve(column_pos.size());
2341
26.6k
    for (size_t block_pos = 0; block_pos < column_pos.size(); ++block_pos) {
2342
22.0k
        const uint32_t schema_pos = column_pos[block_pos];
2343
22.0k
        const auto& column = tablet_schema.column(schema_pos);
2344
22.0k
        if (column.is_variant_type()) {
2345
5.18k
            variant_column_pos.push_back(schema_pos);
2346
5.18k
            variant_schema_pos.push_back(schema_pos);
2347
5.18k
        }
2348
22.0k
    }
2349
2350
4.51k
    if (variant_column_pos.empty()) {
2351
48
        return Status::OK();
2352
48
    }
2353
2354
4.46k
    std::vector<ParseConfig> configs(variant_column_pos.size());
2355
9.73k
    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.27k
        configs[i].deprecated_enable_flatten_nested =
2358
5.27k
                tablet_schema.deprecated_variant_flatten_nested();
2359
5.27k
        configs[i].check_duplicate_json_path = config::variant_enable_duplicate_json_path_check;
2360
5.27k
        const auto& column = tablet_schema.column(variant_schema_pos[i]);
2361
5.27k
        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.27k
        configs[i].parse_to = select_storage_variant_parse_target(column, configs[i]);
2366
5.27k
    }
2367
2368
4.46k
    RETURN_IF_ERROR(parse_and_materialize_variant_columns(block, variant_column_pos, configs));
2369
4.46k
    return Status::OK();
2370
4.46k
}
2371
2372
} // namespace doris::variant_util