Coverage Report

Created: 2026-07-06 17:43

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