Coverage Report

Created: 2026-06-17 07:44

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